Written by 3:42 pm Microsoft, PowerShell, Windows, Windows Server • 3 Comments

Powershell: Working with XML part 2

Powershell Header

After my first post (Powershell: Parsing XML part 1) about working with XML and Powershell, I have create this second post which describes how to create a XML file, Add content to the XML file, remove content from the XML file and save the XML objects as a file.

While I was writing a script which communicates with a webserver, I realized that I need some error handling if the server can not anwser a request from my script. For example if the webserver is down or has to much load.

I created a little retry part (Powershell: Simple retry logic) which retries several times. But if the Server is down for several hours or days your script hangs in a retry loop. Obviously this cant be the solution. After a little bit of thinking a decided to write the data, which I was trying to send, down in a XML file. And the next time the script runs it reads the XML file and tries to send the data again.

Thats the story behind my idea for saving data in a XML file.

Creating a XML object

<pre lang="xml">$FruitList = "&lt;Box&gt;
&lt;Fruit&gt;
&lt;Name&gt;Banana&lt;/Name&gt;
&lt;Color&gt;yellow&lt;/Color&gt;
&lt;/Fruit&gt;
&lt;/Box&gt;"

Save a XML object as a XML file

$FruitList.Save("./myfruitlist.xml")

XML:

<Box>
	<Fruit>
		<Name>Banana</Name>
		<Color>yellow</Color>
	</Fruit>
</Box>

Open a saved XML file

<pre lang="xml">$FruitList = Get-Content ./myfruitlist.xml

Add data to XML object and save it in a XML file

# Copy Object from Banana
[Object]$CopyFruit = FruitList.Box.Fruit | Where-Object {$_.Name -eq "Banana"}
$NewFruit = $CopyFruit.Clone()
# Add Fruit to new Object
$NewFruit.Name = "Apple"
$NewFruit.Color = "green"
# Add Fruit to XML Object
$FruitList.Box.AppendChild($NewFruit)
#Save to XML object ot XML file
$FruitList.Save("./myfruitlist.xml")

XML:

<Box>
	<Fruit>
		<Name>Banana</Name>
		<Color>yellow</Color>
	</Fruit>
	<Fruit>
		<Name>Apple</Name>
		<Color>green</Color>
	</Fruit>
</Box>

Change data from XML Object and save it as XML file

# Change Apple Color
$FruitList.Box.Fruit | Where-Object {$_.Name -eq "Apple"} | ForEach-Object { $_.Color = "red" }
#Save to XML object ot XML file
$FruitList.Save("./myfruitlist.xml")

XML:

<Box>
	<Fruit>
		<Name>Banana</Name>
		<Color>yellow</Color>
	</Fruit>
	<Fruit>
		<Name>Apple</Name>
		<Color>red</Color>
	</Fruit>
</Box>

Remove data from XML Object and save it as XML file

# Remove Banana from Object
$RemoveFruit = $FruitList.Box.Fruit | Where-Object {$_.Name -eq "Banana"}
$FruitList.Box.RemoveChild($RemoveFruit)
#Save to XML object ot XML file
$FruitList.Save("./myfruitlist.xml")

XML:

<Box>
	<Fruit>
		<Name>Apple</Name>
		<Color>green</Color>
	</Fruit>
</Box>

Tags: , , , , , , , , , , , , , , , , , Last modified: July 28, 2010
Close Search Window
Close