EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell XML
Secondary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

PowerShell XML

PowerShell XML

Introduction to PowerShell XML

Extensible Markup Language (XML) is a soft, light-weighted markup language like HTML that defines the set of rules for encoding documents in a format that is both human-readable and machine-readable and used to store and transport data. This language is self-descriptive so PowerShell uses XML generally to retrieve the data from the webpage, modify the content and post it back on the site and even many application configurations are in the XML format that is easy for the application to process the data for machines and can easily be understood and modified by humans.

Syntax

XML Format:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Select-XML cmdlet syntax:

Select-Xml
[-Xml] <XmlNode[]>
[-Path] <String[]>
-LiteralPath <String[]>
-Content <String[]>
[-XPath] <String>
[-Namespace <Hashtable>] [<CommonParameters>]

ConvertTo-XML syntax:

ConvertTo-Xml
[-Depth <Int32>] [-InputObject] <PSObject>
[-NoTypeInformation] [-As <String>] [<CommonParameters>]

XPath Syntax:

This is not only for the PowerShell but it is a global XPath syntax and XPath is a major element in the XSLT standard. XPath is very helpful in retrieving the data from the XML file.

Expression Description
NodeName Selects all nodes with the name “NodeName”
/ Selects from the root node
// Selects Nodes from the entire document with that tag
. Selects the current node
.. Select the parent of the current node
@ Select Attribute

How does XML in PowerShell Works?

PowerShell handles the XML files very efficiently. There are two ways that PowerShell retrieves the data from the XML file.

  • XPath
  • Dot Method.

And for converting a file to XML,

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,527 ratings)
  • ConvertTo-XML

Before we start further explanation, we will use a Sample file (Books.xml ) from Microsoft to read XML data throughout this article.

https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)?redirectedfrom=MSDN

1. Retrieving Data from the XML file

  • Loading XML file

To load the XML file into PowerShell, we can use the First Get-Content command and then typecast into the XML as shown below.

$file = [XML](Get-Content C:\Temp\SampleXML.xml)

Or

[XML]$file = Get-Content C:\Temp\SampleXML.xml

You can also load XML by creating an XML object type and then loading an XML file. For example,

$xml = New-Object -TypeName XML
$xml.Load('C:\Temp\SampleXML.xml')
$xml.Load('C:\Temp\SampleXML.xml')

In the above cases, you will get the output as below,

Output:

PowerShell XML output 1

To check which methods are supported in XML operation, you can check methods using the Get-Member command as shown below.

$xml | Get-Member

a. XPath method

To work with the XPath method, we can use the table shown in the Syntax section. First of all, to retrieve the data of the single node from the entire document, we can use the below command syntax.

$xml.SelectNodes("//NodeName")

In this example, we have nodes like Book, Author, Title, genre, etc. We can select any of them.

$file.SelectNodes('//genre')

Output:

PowerShell XML output 2

Please note that the XML operation is case-sensitive.

To select single node, we can use SelectSingleNode() method.

$xml.SelectSingleNode('//title')

This will select the data from the first node. To select a different node, we need to provide the array number. In PowerShell, the array starts with [0] but in XML, it starts with numbers 1,2,3, and so on.

$xml.SelectSingleNode('//catalog/book[2]')

The above command will select book number 2 from the main catalog.

Output:

PowerShell XML output 3

The below node is selected.

PowerShell XML output 4

You can also directly use the command without specifying the parent node.

$xml.SelectSingleNode('//book[2]')

To use get the above output, we can also use the Select-XML command which works the same way as the above command. For example,

Select-Xml -Xml $xml -XPath "//catalog/book[2]" | Select -ExpandProperty Node

Output:

PowerShell XML output 5

You can also further expand as shown below.

$xml.SelectSingleNode('//catalog/book[2]/author')

Output:

PowerShell XML output 6

b. Dot method

This method is very well known that we are using on daily basis in PowerShell. We have already loaded the XML document at the beginning of this section. We will use now the Dot method for it.

The below command will retrieve book number 2 from the XML document.

This is our sample XML document.

PS C:\> $xml
xml           catalog
---           -------
version="1.0" catalog
Command to retrieve book number:2
$xml.catalog.book[2]

Output:

PowerShell XML output 7

2. ConvertTo the XML file

To convert any possible output to the XML, you can use the convertTo-XML command.

$services = Get-Service | ConvertTo-Xml
$services = Get-Service | ConvertTo-Xml
$services

Output:

output 8

To expand further, we can use any of the methods (Xpath or Dot method). For example,

$services.Objects.Object[1] | Select -ExpandProperty Property

Output:

output 9

Examples

Here are the follwoing examples mention below

1. To load the entire content of the XML

To load the entire XML using

$xml = [xml](Get-Content C:\Temp\SampleXML.xml)
$xml.SelectNodes('/catalog') | Select -ExpandProperty Book

Output:

output 10

2. To search for the specific attribute

To search the specific attribute we can use the below command. It will search for the book id ‘bk112’.

$xml.SelectNodes('//catalog/book') | where{$_.id -eq 'bk112'}

Output:

output 11

3. Finding attribute using Dot Method

The example shown above can also be written through the Dot method as shown below.

$xml.catalog.book |where{$_.id -eq "bk112"}

Output:

output 12

4. To add a new element in the file

We will add the new element to the existing file.

$file = 'C:\Temp\SampleXML.xml'
$xml = [xml](Get-Content $file)

The below command will create a “Book1” named new element in the XML file.

$newelement = $xml.CreateElement("Book1")
$newelement

Output:

output 13

Once it is created, the second task is to append it to the existing document.

$xml.catalog.AppendChild($newelement)

Output:

output 14

Once you appended the element, next is to save the file using the below command.

$xml.Save($file)

Now let’s test if the new element appears in the XML document or not.

$xml.catalog

Output:

output 15

5. Create a new node and set its attributes

In this example, we will add a new book name “XML Introduction” with the code shown below.

$file = "C:\temp\SampleXML.xml"
$xml = [xml](Get-Content $file)
$newbookelement = $xml.catalog.AppendChild($xml.CreateElement("book"))
$newbookelement.SetAttribute("id","bk113")
$newAuthorelement = $newbookelement.AppendChild($xml.CreateElement("author"))
$newAuthorelement.AppendChild($xml.CreateTextNode("Dan Harley")) | Out-Null
$newtitleelement = $newbookelement.AppendChild($xml.CreateElement("title"))
$newtitleelement.AppendChild($xml.CreateTextNode("XML Introduction")) | Out-Null
$xml.Save(($file))

Output:

output 16

You can also check the same in the XML file.

output 17

Conclusion

XML files are the best way to provide the configuration data. Most applications use XML files for configuration and even to interact with the RestAPI methods, many websites have XML as the API output.

Recommended Articles

This is a guide to PowerShell XML. Here we discuss that  XML files are the best way to provide the configuration data. You may also have a look at the following articles to learn more –

  1. PowerShell Sleep
  2. PowerShell scriptblock
  3. PowerShell Filter
  4. PowerShell Registry
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more