Powershell: replace content in xml

Hi,

I'd like to automate WSUS deploy. That can be done using an xml: https://www.petri.com/automating-wsus-2016-installation-with-powershell
So now I'd like to change the xml with the servername.

In other words, I need to replace the computername (Servernamexyz in my example, can change overtime) in this xml.

So I'd get the xml in $XML = get-content c:\myxml.xml
tags to replace are
<S N="ServerName">Servernamexyz</S>
and  <S N="PSComputerName">Servernamexyz</S>

How do I replace <S N="ServerName"> whatever </s> and  <S N="PSComputerName">Whatever</S> ?
I can then write result back to xml.

Thanks for your input.
J.
janhoedtAsked:
Who is Participating?
 
oBdACommented:
This is a bit more complicated than usual, because the XML has a namespace, so you need to use a namespace manager:
$xmlPath = 'C:\Temp\foo.xml'
$newServerName = 'foo.contoso.com'

$xml = [xml](Get-Content -Path $xmlPath)
[System.Xml.XmlNamespaceManager]$nsm = $xml.NameTable
$nsm.AddNamespace('ns', $xml.Objs.GetAttribute('xmlns'))
$xml.SelectNodes("//ns:S[@N='ServerName' or @N='PSComputerName']", $nsm) | ForEach-Object {$_.InnerText = $newServerName}
$xml.Save($xmlPath)

Open in new window

1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.