How to check whether a node exists or not using powershell without getting exception?

二次信任 提交于 2019-12-10 04:35:45

问题


I am trying to check whether a particular node exists or not like follows.

In my config file there is a node named client ,it may or may not available.

If it is not available i have to add it.

    $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) 

    }

The condition i am checking may return array.

i would like to check whether the client node available before or not?


回答1:


Why can't you just do something like:

$xmldata = [xml](Get-Content $webConfig)    
$FullSearchStr = $xmldata.configuration.'system.serviceModel'    



回答2:


You can try the SelectSingleNode method:

$client = $xmldata.SelectSingleNode('//configuration/system.serviceModel/Client')

if(-not $client)
{
    $client = $xmldata.CreateElement('Client')
    ...
}



回答3:


You can also use 'count' like a boolean

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
}


来源:https://stackoverflow.com/questions/13031110/how-to-check-whether-a-node-exists-or-not-using-powershell-without-getting-excep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!