|
# A script that manipulates xml documents just like augeas |
|
# Written by spuder, borrowed parts from https://ask.puppetlabs.com/question/4749/augeas-or-alternative-xml-modification-on-windows/ |
|
# .\xmlModify.ps1 -filename "c:\foobar.xml" -xpath "/configuration/foo" -element "bacon" -attribute_key "isGood" -attribute_value "true" -text "I love bacon" -verbose |
|
|
|
#<?xml version="1.0" encoding="utf-8"?> |
|
#<configuration> |
|
# <foo/> |
|
# <bacon isGood="true">I love bacon</bacon> |
|
|
|
[CmdletBinding()] |
|
|
|
param ( |
|
[string] $filename = $(throw "filename is a required parameter"), |
|
[string] $xpath = $(throw "xpath is a required parameter"), |
|
[string] $element = $(throw "node is a required parameter"), |
|
[string] $attribute_key = "", |
|
[string] $attribute_value = "", |
|
[string] $text = "" |
|
) |
|
|
|
write-verbose "Received arguments:" |
|
write-verbose "filename: ""$filename""" |
|
write-verbose "xpath: ""$xpath""" |
|
write-verbose "element: ""$element""" |
|
write-verbose "attribute_key: ""$attribute_key""" |
|
write-verbose "attribute_value: ""$attribute_value""" |
|
write-verbose "text: ""$text""`n" |
|
|
|
# Get xml Document |
|
$xml = [xml](Get-Content $filename) |
|
|
|
# If path exists, but not node, create it |
|
# If path and node don't exist, error and exit |
|
if ($xml.SelectNodes($xpath) ) |
|
{ |
|
Write-Verbose "Found $filename $xpath" |
|
if (-Not $xml.SelectSingleNode("$xpath/$element") ) |
|
{ |
|
Write-Host "$($element) does not exist in $($xpath), appending" |
|
$child = $xml.CreateElement($element) |
|
$xml.SelectSingleNode($xpath).AppendChild($child) > $null |
|
} |
|
} |
|
else |
|
{ |
|
echo "Could not find $($element) in $($filename)" |
|
exit 1 |
|
} |
|
|
|
# Update node value |
|
$xmlItem = $xml.SelectSingleNode("$($xpath)/$($element)") |
|
$xmlItem.SetAttribute($attribute_key, $attribute_value) |
|
|
|
#Update text if provided |
|
if ($($text) -ne "") { |
|
$xmlItem.set_InnerXML("$text") |
|
} |
|
|
|
$xmlitem |
|
|
|
# Overwrite file |
|
$xml.save($filename) |