0

A bit of a PowerShell neophyte here, so please be kind. I am creating a PS script which is helping me to document my environment. What I am trying to do is get the names of all of an object's properties and populate an XML document with the property names and corresponding values. For example:

PS C:\> $stuff = Get-SomeStuff
PS C:\> $stuff
Name: foo
Version: 1.0

The output XML would look like this:

<rootNode>
    <stuff>
        <Name>foo</Name>
        <Version>1.0</Version>
    </stuff>
</rootNode>

Essentially I want to use the $stuff property names to substitute for the properties when retrieving the object properties. Essentially I need to dynamically substitute the property name with the extracted name. My code looks like this:

$stuff = Get-SomeStuff
CreateXML $rootnode,"stuff",$stuff

Function CreateXML ($rootNode, $nodeName, $category){
    $subRootNode = $xml.CreateElement($nodeName)
    $catProps = $stuff | Get-Member -MemberType Property | Select -ExpandProperty Name
    foreach ($prop in $catProps){
        $newNode = $xml.CreateElement($prop)
        $newNode.Text = $category.{$prop} #--- THIS IS THE LINE CAUSING PROBLEMS
        $subRootNode.AppendChild($newNode)
    }
$rootNode.AppendChild($subRootNode)
}

Any help is greatly appreciated, as there are thousands of properties I have to capture across multiple nodes.

5
  • Maybe I'm just missing it, but where does $category come from? Commented May 31, 2013 at 17:08
  • 1
    What is Get-SomeStuff? And what problems exactly does $category.{$prop} cause? Commented May 31, 2013 at 17:09
  • Actually, it's easier than you're trying. $category.$prop should work. Commented May 31, 2013 at 18:02
  • Get-SomeStuff was just a dummy cmdlet to simplify the explanation. In terms of the problem it causes, it doesn't work. I was able to establish that the output of doing it that way would dump property typing, not the property itself. Commented May 31, 2013 at 18:24
  • Mike, I tried that originally but nothing gets sent through the output. Commented May 31, 2013 at 18:27

1 Answer 1

2

Try this way:

[xml]$xml = '<rootNode></rootNode>'    

$stuff | foreach {

    $node = $xml.CreateElement('stuff')

    $_.psobject.properties | foreach{
        $prop = $xml.CreateElement($_.Name)
        $prop.InnerText = $_.value
        $node.AppendChild($prop)
    }

    $xml.DocumentElement.AppendChild($node)   

}

$xml
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.