xml node exists using variables in powershell

Question!

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."



Answers
I think you want $users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[. = '$mailbox']").



This video can help you solving your question :)
By: admin