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:


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)
$mailboxes = $xmlData.SelectSingleNode("./Profiler/Mailboxes")

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

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

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