powershellxmltocsv

Need help converting XML to CSV


I need to convert the below XML to CSV

<App>
    <SecurityGroup name="Admin">
        <Member username="John1" displayName="JohnDoe"/>
        <Member username="Jane1" displayName="JoeDoe"/>
    </SecurityGroup>
</App>

I tried the below one as well

$xml.app.childnodes | Select-Object @(
    @{l="name";e={ $_.member.username}},
    @{l="display";e={ $_.member.displayname }},
    @{l="group";e={ $_.name }} 
) | Export-CSV "c:/test.csv"

The format looks good but the username field and display name are all coming in the same field instead of individual rows

Security Group    Username           Displayname
Admin             John1 Jane1        JohnDoe JaneDoe

I need the below format

SecurityGroup Username Displayname
Admin John1 JohnDoe
Admin Jane1 JoeDoe

Solution

  • In the calculated properties specified as Select-Object arguments, $_.member creates an array of of all Member elements (due to member access enumeration), which is why your CSV contains multiple property values per field.

    What you want to do instead, is descend down to the Member elements already in the first member access chain:

    $xml.app.childnodes.member | Select-Object @(
        @{ l='name'; e='username'}
        @{ l='display'; e='displayname'}
        @{ l='group'; e={ $_.ParentNode.name }} 
    ) | Export-CSV "c:/test.csv"
    

    Output:

    "name","display","group" 
    "John1","JohnDoe","Admin"
    "Jane1","JoeDoe","Admin" 
    

    Notes: