How to iterate through XML in Powershell?

后端 未结 2 585
你的背包
你的背包 2020-12-09 01:49

I have this XML document in a text file:



  
         


        
                      
相关标签:
2条回答
  • 2020-12-09 01:54

    PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

    [xml]$xml = Get-Content $serviceStatePath
    $nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
    $nodes | ForEach-Object {$_.Node.'#text'}
    

    Or shorter

    [xml]$xml = Get-Content $serviceStatePath
    Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
      % {$_.Node.'#text'}
    
    0 讨论(0)
  • 2020-12-09 02:11

    You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

    $xml = (select-xml -xpath / -path stack.xml).node
    $xml.objects.object.property
    

    Or just this, xpath is case sensitive. Both have the same output:

    $xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
    $xml
    
    
    Name         Type                                                #text
    ----         ----                                                -----
    DisplayName  System.String                                       SQL Server (MSSQLSERVER)
    ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
    DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
    ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
    
    0 讨论(0)
提交回复
热议问题