简体   繁体   中英

xml node exists using variables in powershell

I am trying to determine if a Mailbox with a certain DisplayName exists in my powershell script (see example xml below). I can find the node if I hard-code the value, but I have not been able to pass this value as a parameter. I have tried various ways of escaping, using single quotes and double, but none of it is going the right way.

The ultimate goal is to create the Mailbox node if one doesn't exist with the same DisplayName. There may be 0 or more Mailbox nodes.

Here's a sample xml:

<Profiler>
  <Mailboxes>
    <Mailbox>
      <DisplayName>django</DisplayName>
    </Mailbox>
  </Mailboxes>
</Profiler>

This is the piece of code, I want executed if the node doesn't exist:

$newMailbox = $xmlData.CreateElement("Mailbox")
$newDisplayName = $xmlData.CreateElement("DisplayName")
$newDisplayNameText = $xmlData.CreateTextNode($mailboxName)
$newDisplayName.AppendChild($newDisplayNameText)
$newMailbox.AppendChild($newDisplayName)
$mailboxes = $xmlData.SelectSingleNode("./Profiler/Mailboxes")
$mailboxes.AppendChild($newMailbox)

This piece of code works:

$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[text() = 'django']")
write-host $users.count

output from script: 1

This doesn't:

$mailboxName = "django"
$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[text() = $mailboxName]")
write-host $users.count 

output from script: 0

I also tried this:

$mailboxName = "django"
$users= $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox[DisplayName = $mailbox]")

output from script: Exception calling "SelectNodes" with "1" argument(s): "Expression must evaluate to a node-set."

我认为您需要$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[. = '$mailbox']")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM