Working with XML in PowerShell
Create an XML object from an XML file
Cast in [xml]
to create an XML object.
PS> $xml = [xml](Get-Content .\Settings.xml -Encoding UTF8)
PS> $xml
xml project
--- -------
version="1.0" encoding="UTF-8" project
The following is an XML file that I prepared.
PS> Get-Content .\Settings.xml -Encoding UTF8
<?xml version='1.0' encoding='UTF-8'?>
<project>
<view>
<includeRegex>(?i).*DT-4000.*</includeRegex>
</view>
<deployJob>
<jobName>DT-4000_TestDeploy</jobName>
<p4Stream>//stream_depot/LM_CIV_DT-4000_TestDeploy</p4Stream>
</deployJob>
</project>
Referencing and rewriting the value of an XML object
Use dot (.
) to refer to the value of an XML object.
PS> $xml.project.deployJob.jobName
DT-4000_TestDeploy
PS> $xml.project.deployJob.jobName = "DT-4000_Deploy"
PS> $xml.project.deployJob.jobName
DT-4000_Deploy
Saving an XML object to a file
Use $xml.Save($Path)
.
If you want to specify the encoding, another way.
PS> $Path = "C:\Users\miajimyu\Desktop\Output.xml"
PS> $xml.Save($Path)
PS> Get-Content -LiteralPath $Path
<?xml version="1.0" encoding="UTF-8"?>
<project>
<view>
<includeRegex>(?i).*DT-4000.*</includeRegex>
</view>
<deployJob>
<jobName>DT-4000_Deploy</jobName>
<p4Stream>//stream_depot/LM_CIV_DT-4000_TestDeploy</p4Stream>
</deployJob>
</project>
Convert an XML object to a string
You can use $xml.OuterXML
to turn an XML object into a string.
# Example: Based on an existing job in Jenkins, edit the XML and create a new job
PS> $text = java -jar jenkins-cli.jar -s "http://localhost:8080/" get-job Test
PS> $text
<?xml version='1.0' encoding='UTF-8'?>
<project>
<actions/>
<description>Description</description>
<keepDependencies>false</keepDependencies>
<properties>
<org.jvnet.hudson.plugins.shelveproject.ShelveProjectProperty plugin="shelve-project-plugin@1.5"/>
</properties>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers/>
<concurrentBuild>false</concurrentBuild>
<builders/>
<publishers/>
<buildWrappers/>
</project>
PS> $xml = [xml]$text
PS> $xml
xml project
--- -------
version="1.0" encoding="UTF-8" project
PS> $xml.project.description
Description
PS> $xml.project.description = "New Description"
PS> $xml.OuterXml | java -jar jenkins-cli.jar -s "http://localhost:8080/" create-job NewTest