Emit-XML

I was writing a demo yesterday and needed a quick and dirty way to generate some XML so I wrote the function below.  This highlights a couple of changes that are coming up in CTP3 that I thought I would preview.


1) The keyword “cmdlet” is going away and we’ll just have “function”.  Notice that now you can specify the [Parameter()]  attribute on parameters.  When you do that, we treat the function like a cmdlet.
2) Here-strings can now NEST!  Look at how simple the code becomes when you do this.  I think you are going to find this to be one of the more important and powerful new features of PS V2.  It provides incredible power in a very pithy (and natural) way.



The first Here-String starts the XML document with a “<Object>”.   Because we use a HERE-STRING with double (vs single) quotes, we expand variables $var and subexpressions $( statement;statement; …).  The next thing is an expression which contains a foreach.  That calculates the name and value of the property and then uses an embedded Here-String to emit that text.


 


function Emit-XML
{
Param ([Parameter(Mandatory=$true,
   ValueFromPipeline=$true)]$object)


@”
<Object>
$(    
    foreach ($p in $object |Get-Member -type *Property)
    {
        $Name  = $p.Name
        $Value = $Object.$Name   
        @”
`t<$Name>$Value</$Name>`n
“@
     }
)
</Object>
“@
}


 


Here is an usage example:


PS> gsv alg | Emit-xml
<Object>
        <Name>ALG</Name>
        <CanPauseAndContinue>False</CanPauseAndContinue>
        <CanShutdown>False</CanShutdown>
        <CanStop>False</CanStop>
        <Container></Container>
        <DependentServices></DependentServices>
        <DisplayName>Application Layer Gateway Service</DisplayName>
        <MachineName>.</MachineName>
        <ServiceHandle>SafeServiceHandle</ServiceHandle>
        <ServiceName>ALG</ServiceName>
        <ServicesDependedOn></ServicesDependedOn>
        <ServiceType>Win32OwnProcess</ServiceType>
        <Site></Site>
        <Status>Stopped</Status>
</Object>


I have to admit – I am VERY excited by some of the stuff we are lined up to deliver to you in V2.  You take that kind of power and give it to this community and exciting things are going to happen.  I can’t wait to see all the things you guys do with this stuf!


Jeffrey Snover [MSFT]
Windows Management Partner Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx