How to check if node exists or not using powershell without exception?

I am trying to check if a specific node exists or does not like it.

There is a client in my configuration file called node, it may or may not be available.

If it is not available, I must 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 that I am checking can return an array.

I would like to check if the node client is available before or not?

+6
powershell
source share
3 answers

Why can't you just do something like:

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

You can try the SelectSingleNode method:

 $client = $xmldata.SelectSingleNode('//configuration/system.serviceModel/Client') if(-not $client) { $client = $xmldata.CreateElement('Client') ... } 
+8
source share

You can also use 'count' like 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 } 
+2
source share

All Articles