Example of work with XML in PowerShell

By PowerShell

My colleague has struggled with creating an XML file according to a template. He needed to prepare the XML for “Remote Desktop Connection Manager” with all of the production servers.

Below you can see how the template looks. A server node was a part that was required to be copied and modified. In the complete file should appear a new section for each server.

Probably you don’t need a script like that but I decided to share it because it shows how easily we can modify XML files. You will find in the script methods how to convert XML to an object, clone a specific node, and modify values of XML elements as well.

param(
    $RdgTemplatePath = 'C:\01_Temp\RDCMan\template.rdg',
    $ComputerFilePath = 'C:\01_Temp\RDCMan\servers.txt',
    $RdgOutputPath = 'C:\01_Temp\RDCMan\RDCMan.rdg'
)
 
[xml]$File = Get-Content $RdgTemplatePath
$Computers = Get-Content $ComputerFilePath
 
# The cloneNode() method creates a copy of a specified node.
$CloneServer = $File.RDCMan.file.server.CloneNode($true)
 
foreach ($ComputerName in $Computers)
{
    Write-Verbose "Adding the $ComputerName" -Verbose
 
    # Modifying elements
    $CloneServer.properties.displayName = $ComputerName
    $CloneServer.properties.name = "$ComputerName.domain.local"
 
    # The appendChild() method adds a child node to an existing node.
    $File.RDCMan.file.AppendChild($CloneServer) | Out-Null
    $CloneServer = $File.RDCMan.file.server[-1].CloneNode($true)
}
 
# Saving a new file
$File.Save($RdgOutputPath)

22 Najważniejsze Wskazówki Pisania Skryptów PowerShell

No comments yet.

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *

Witryna wykorzystuje Akismet, aby ograniczyć spam. Dowiedz się więcej jak przetwarzane są dane komentarzy.

× Close