如何在不出现异常的情况下检查节点是否存在或未使用powershell?
我试图检查某个特定节点是否存在,如下所示 在我的配置文件中有一个名为client的节点,它可能可用,也可能不可用 如果它不可用,我必须添加它如何在不出现异常的情况下检查节点是否存在或未使用powershell?,powershell,powershell-2.0,Powershell,Powershell 2.0,我试图检查某个特定节点是否存在,如下所示 在我的配置文件中有一个名为client的节点,它可能可用,也可能不可用 如果它不可用,我必须添加它 $xmldata = [xml](Get-Content $webConfig) $xpath="//configuration/system.serviceModel" $FullSearchStr= Select-XML -XML $xmldata -XPath $xpath If ( $Fu
$xmldata = [xml](Get-Content $webConfig)
$xpath="//configuration/system.serviceModel"
$FullSearchStr= Select-XML -XML $xmldata -XPath $xpath
If ( $FullSearchStr -ne $null) {
#Add client node
$client = $xmldata.CreateElement('Client')
$client.set_InnerXML("$ClientNode")
$xmldata.configuration."system.serviceModel".AppendChild($client)
$xmldata.Save($webConfig)
}
我正在检查的条件可能返回数组
我想检查客户端节点之前是否可用?您可以尝试SelectSingleNode方法:
$client = $xmldata.SelectSingleNode('//configuration/system.serviceModel/Client')
if(-not $client)
{
$client = $xmldata.CreateElement('Client')
...
}
为什么你不能像这样做:
$xmldata = [xml](Get-Content $webConfig)
$FullSearchStr = $xmldata.configuration.'system.serviceModel'
您还可以像布尔值一样使用“count”
if ($xmldata.SelectSingleNode('//configuration/system.serviceModel/Client').Count)
{
The count is 1 or more, so it exists
}
else
{
The count is 0, so it doesn't exists
}
如果xpath作为变量传递,如$xpath='//configuration/system.serviceModel/client'$client=$xmldata.SelectSingleNode($xpath),则该条件会成功,即使“client”节点已存在,但如果直接传递xpath,则其工作正常。奇特的逻辑!!!我错过了什么MVP?必须打包才能拿到分数
if(@($xmldata.SelectSingleNode('//configuration/system.serviceModel/Client')).Count-gt 0)