Tag Archives: Creating Custom XML in PowerShell

How to Create XML file for the current Running services using Powershell

As a System Admin, I came up with a requirement of creating an XML file for a currently running process from Multiple systems as output using PowerShell code. Post this, the same XML file will be consumed by an external trend reporting process.

The ConvertTo-Xml cmdlet creates an XML-based representation of one or more .NET objects. To use this cmdlet, pipe one or more objects to the cmdlet, or use the InputObject parameter to specify the object. We also use Export-Clixml for the same scenario, we will review this in the upcoming article.

In this article, I am going to explain with simple XML creation method using XmlWrite and here we want to get current running service information using Get-Service from each computer and save the results to an XML file.

STEP #1: Get currently Running service using the Get-Service cmdlet

$xmlString = Get-Service | Where-Object {$_.Status -eq “Running”}

STEP #2: Convert the output in the ConvertTo-XML with As parameter

Technically ConvertTo-XML is working but in its current usage, it is returning an XML document object and only showing the top two properties. 

ConvertTo-XML -as String, this command converts the process objects that represent all of the services on the computer into an XML document and finally convert as String as output

$xmlString = Get-Service | Where-Object {$_.Status -eq “Running”} | ConvertTo-XML -as String

You can use -Depth parameter, which specifies how many levels of contained objects are included in the XML representation. The default value is 1.

STEP #3: Output the String in an XML file on the specific location

$xmlString | Out-File -FilePath C:\dotnet-helpers\MyServices.xml -encoding utf8

Entire Code

################################################################################### 
#Project : How to Create XML file for the current Running services using Powershell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 [irp]
#E-Mail: mail2thiyaguji@gmail.com 
###################################################################################

$xmlString = Get-Service | Where-Object {$_.Status -eq "Running"} | ConvertTo-XML -as String
$xmlString | Out-File -FilePath C:\dotnet-helpers\MyServices.xml -encoding utf8

Output

 

Creating a Simple XML Document using Powershell XmlWriter()

Recently, I came up with a requirement of creating an XML file as output using PowerShell code. I want to get some service information from each computer and save the results to an XML file. Post this, the XML file will be consumed by an external trend reporting process. In this article, I am going to explain with simple XML creation method using XmlWrite with some static inputs.

STEP #1: Create & Set The Formatting with XmlWriterSettings class

First, we need to get an XmlTextWriter object to create the XML and assign the Indent values as true to make the elements to be arranged in a new line. The XmlWriterSettings class provides properties that control data conformance and output format.

$xmlObjectsettings = New-Object System.Xml.XmlWriterSettings
#Indent: Gets or sets a value indicating whether to indent elements.
$xmlObjectsettings.Indent = $true
$xmlObjectsettings.IndentChars = ” “

STEP #2: Set the XML File Path and Create The Document

# Set the File path & Create The Document
$XmlFilePath = “C:\dotnet-helpers\MyXmlFile.xml”
$XmlObjectWriter = [System.XML.XmlWriter]::Create($XmlFilePath, $xmlObjectsettings)

STEP #3 : Write the XML Declaration

When WriteStartDocument is called the writer validates that what you are writing is a well-formed XML document.For example, it checks that the XML declaration is the first node, that one and only one root-level element exists, and so on. If this method is not called, the writer assumes an XML fragment is being written and applies no root level rules.

#Write the XML delcaration.
$XmlObjectWriter.WriteStartDocument()

STEP #4: Start the Root Element and build with child nodes

In this step we are going to form the HTML elments using the WriteStartElement , WriteEndElement() ,WriteElementString , WriteComment…

XmlObjectWriter.WriteComment(“writes out a start tag with the specified local name.”)
$XmlObjectWriter.WriteStartElement(“BaseSettings“) # <– BaseSettings

$XmlObjectWriter.WriteStartElement(“ConfigSettings“) # <– Start ConfigSettings
$XmlObjectWriter.WriteElementString(“India”,”200$”)
$XmlObjectWriter.WriteElementString(“UAE”,”150$”)

$XmlObjectWriter.WriteStartElement(“ChildConfigSettings“) # <– Start ChildConfigSettings
$XmlObjectWriter.WriteElementString(“UK”,”250$”)

$XmlObjectWriter.WriteEndElement() # <– End ChildConfigSettings
$XmlObjectWriter.WriteEndElement() # <– End ConfigSettings
$XmlObjectWriter.WriteEndElement() # <– End BaseSettings

STEP #5 : Finally close the XML Document

$XmlObjectWriter.WriteEndDocument()
$XmlObjectWriter.Flush()
$XmlObjectWriter.Close()

Full Code

############################################################################
#Project: Creating a Simple XML Document using XmlWriter()
#Developer: Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 [irp]
#E-Mail: mail2thiyaguji@gmail.com 
###########################################################################

# Create & Set The Formatting with XmlWriterSettings class
$xmlObjectsettings = New-Object System.Xml.XmlWriterSettings
#Indent: Gets or sets a value indicating whether to indent elements.
$xmlObjectsettings.Indent = $true
#Gets or sets the character string to use when indenting. This setting is used when the Indent property is set to true.
$xmlObjectsettings.IndentChars = "    "

# Set the File path & Create The Document
$XmlFilePath = "C:\dotnet-helpers\MyXmlFile.xml"
$XmlObjectWriter = [System.XML.XmlWriter]::Create($XmlFilePath, $xmlObjectsettings)

# Write the XML declaration and set the XSL
$XmlObjectWriter.WriteStartDocument()


# Start the Root Element and build with child nodes
$XmlObjectWriter.WriteComment("writes out a start tag with the specified local name.")
$XmlObjectWriter.WriteStartElement("BaseSettings") # <-- BaseSettings
  
    $XmlObjectWriter.WriteStartElement("ConfigSettings") # <-- Start ConfigSettings

        $XmlObjectWriter.WriteElementString("India","200$")
        $XmlObjectWriter.WriteElementString("UAE","150$")

        $XmlObjectWriter.WriteStartElement("ChildConfigSettings") # <-- Start ChildConfigSettings 
            $XmlObjectWriter.WriteElementString("UK","250$")
            $XmlObjectWriter.WriteEndElement() # <-- End ChildConfigSettings

    $XmlObjectWriter.WriteEndElement() # <-- End ConfigSettings

$XmlObjectWriter.WriteEndElement() # <-- End BaseSettings 

# Finally close the XML Document
$XmlObjectWriter.WriteEndDocument()
$XmlObjectWriter.Flush()
$XmlObjectWriter.Close()

Output XML File :

There are additional ways to create custom XML. and there are plenty of methods that we can experiment. We will discuss in the upcoming posts