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

Output