0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

According to ss64.com/ps/syntax-esc.html and from what I've seen, it won't work - anything inside a single-quoted string won't be evaluated. And if I try double quotes, I get new errors
In my understanding the powershell string in my code samples is delimited by double quotes so powershell will do variable interpolation. The single quotes are inside the double quoted string, and they are in their for XPath, so that the argument passed to SelectNodes will be the string ./Profiler/Mailboxes/Mailbox/DisplayName[. = 'jango'] and not the string ./Profiler/Mailboxes/Mailbox/DisplayName[. = jango] as the latter would compare DisplayName to an XML element named jango and not the string value jango.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.