Parse xml to variable in powershell

Diwas K 26 Reputation points
2022-11-04T14:25:44.387+00:00

HI All,
I have an xml file that looks like this:
<AccountRequest application="Active Directory" op="Create" nativeIdentity="CN=estest,OU=Users,OU=Test User Provisioning,DC=testtcbna,DC=net">
<AttributeRequest op="Set">
<Attributes>
<Map>
<entry key="Employee id" value="109844" />
<entry key="Manager" value="Testerman,Maria" />
<entry key="Location" value="Austin - San Jacinto: Floor 2" />
<entry key="isManager" value="No" />
<entry key="Department" value="Information Security" />
<entry key="Associate id" value="30009" />
<entry key="Effective Date" value="12/15/2021" />
<entry key="Name" value="Testerman, Esteban" />
</Map>
</Attributes>
</AttributeRequest>
</AccountRequest>

How do I get values for "Employee id" , "manager" and so on and assign it to a variable?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} vote

Answer accepted by question author
  1. Andreas Baumgarten 129.4K Reputation points MVP Volunteer Moderator
    2022-11-04T15:10:15.013+00:00

    Hi @Diwas K ,

    maybe this helps to get started (the test.xml contains the xml structure you posted in your question):

    $a = Select-Xml -Path .\Junk\test.xml -XPath "//entry" | Select-Object -ExpandProperty Node  
    # Get Employee Id   
    $empId = ($a | Where-Object { $_.key -eq 'Employee Id' }).Value  
    $empId  
    # Get Manager  
    $manager = ($a | Where-Object { $_.key -eq 'Manager' }).Value  
    $manager  
    

    A more dynamic option:

    $a = Select-Xml -Path .\Junk\test.xml -XPath "//entry" | Select-Object -ExpandProperty Node  
    $a | ForEach-Object {  
        Remove-Variable -Name $($_.Key)  
        New-Variable -Name $($_.Key) -Value $($_.Value)  
    }  
    $manager  
    ${Employee Id}  
    $name  
    ${Effective Date}  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 48,026 Reputation points
    2022-11-04T15:14:28.34+00:00

    You can use the Select-XML and XPath:

    $xml = [xml](Get-Content c:\junk\xxxml.xml -Raw)  
      
    $Eid = Select-Xml -XML $xml -XPath "//*[@key='Employee id']"  
    $Mgr = Select-Xml -XML $xml -XPath "//*[@key='Manager']"  
      
    "$($Eid.node.key) = $($Eid.node.value)"  
    "$($Mgr.node.key) = $($Mgr.node.value)"  
    
    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.