tirsdag den 21. februar 2012

Hello Powershell xml

I remember when I started looking at xml and I thought that I had to write a parser myself. Then I started looking at mssql which made it a lot easier. But it still had some bugs. Then I tried powershell and xml. This is quite smart.

Lets see. To read a text file, we need to call the Get-Content. This returns an object and by putting the [XML] in front of the returned object, we can use it as a structure of objects. Lets see, first we'll make an xmlfile with a couple of services in them:



wininit explorer



Let's just read the information on the process, so we read the xml file and gets the process info for each service in the xml-file


[xml]$xmlFile=Get-Content "D:\temp\test.xml"
$xmlFile.Services.Service | ForEach-Object {     Get-Process $_ | Format-List }


Voila, we now have read an xmlfile and tested the processes. But what if we want to write the Ids back to an xmlfile.. 

Lets see - first we make an xml template of what we want. 







and lets use the xml in another way.. just for fun, you can still use [XML]


cls
[xml]$xmlFile=Get-Content "D:\temp\test.xml"
$processFile=New-Object xml
$processFile.Load("D:\temp\processes.xml")
$newProcess=(@($processFile.processes.process)[0]).Clone()
Write-Host $newProcess.pId
$xmlFile.Services.Service | ForEach-Object {
    Get-Process $_ | ForEach-Object {
        $newProcess = $newProcess.Clone()
        $newProcess.Id = $_.Id.ToString()
        write-host $newProcess.Id
        $processFile.processes.AppendChild($newProcess)
    }
}
$processFile.processes.RemoveChild($processFile.processes.process[0])
$processFile.Save("D:\temp\proc.xml")

This reads from the first xmlfile, opens the next as a template. Makes a cloneable object, clones it and inserts values. It appends the new object to the xml and at last it removes the first child as it was the template and voila, we have ourselves a written xml



 
    844   
    4056