Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 992
Samselvaprabu Avatar asked Oct 23 '12 13:10

Samselvaprabu


2 Answers

You can try the SelectSingleNode method:

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

if(-not $client)
{
    $client = $xmldata.CreateElement('Client')
    ...
}
like image 161
Shay Levy Avatar answered Sep 26 '22 21:09

Shay Levy


Why can't you just do something like:

$xmldata = [xml](Get-Content $webConfig)    
$FullSearchStr = $xmldata.configuration.'system.serviceModel'    
like image 21
Andrey Marchuk Avatar answered Sep 25 '22 21:09

Andrey Marchuk