xml 节点存在于 powershell 中使用变量
xml node exists using variables in powershell
我正在尝试确定我的 powershell 脚本中是否存在具有特定 DisplayName 的邮箱(参见下面的示例 xml)。如果我对值进行硬编码,我可以找到该节点,但我无法将此值作为参数传递。我尝试了各种转义方式,使用单引号和双引号,但是 none 是正确的方式。
最终目标是创建邮箱节点(如果不存在具有相同显示名称的邮箱节点)。可能有 0 个或多个邮箱节点。
这是一个示例 xml:
<Profiler>
<Mailboxes>
<Mailbox>
<DisplayName>django</DisplayName>
</Mailbox>
</Mailboxes>
</Profiler>
这是一段代码,如果节点不存在我想执行:
$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)
这段代码有效:
$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[text() = 'django']")
write-host $users.count
output from script: 1
这不是:
$mailboxName = "django"
$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[text() = $mailboxName]")
write-host $users.count
output from script: 0
我也试过这个:
$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']")
.
我正在尝试确定我的 powershell 脚本中是否存在具有特定 DisplayName 的邮箱(参见下面的示例 xml)。如果我对值进行硬编码,我可以找到该节点,但我无法将此值作为参数传递。我尝试了各种转义方式,使用单引号和双引号,但是 none 是正确的方式。
最终目标是创建邮箱节点(如果不存在具有相同显示名称的邮箱节点)。可能有 0 个或多个邮箱节点。
这是一个示例 xml:
<Profiler>
<Mailboxes>
<Mailbox>
<DisplayName>django</DisplayName>
</Mailbox>
</Mailboxes>
</Profiler>
这是一段代码,如果节点不存在我想执行:
$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)
这段代码有效:
$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[text() = 'django']")
write-host $users.count
output from script: 1
这不是:
$mailboxName = "django"
$users = $xmlData.SelectNodes("./Profiler/Mailboxes/Mailbox/DisplayName[text() = $mailboxName]")
write-host $users.count
output from script: 0
我也试过这个:
$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']")
.