Parse xml to variable in powershell

Diwas K 26 Reputation points

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">
<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" />

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

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,431 questions
0 comments No comments
{count} vote

Accepted answer
  1. Andreas Baumgarten 99,466 Reputation points MVP

    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  
    # Get Manager  
    $manager = ($a | Where-Object { $_.key -eq 'Manager' }).Value  

    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)  
    ${Employee Id}  
    ${Effective Date}  


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

    Andreas Baumgarten

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 45,416 Reputation points

    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.