user829174 user829174 - 2 months ago 12x
PowerShell Question

How to read xml value via cmd / Powershell

I have the following xml format

How can I read the value of

Tar Path

<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsd="" xmlns:xsi="">
<Bar Path="c:\program files\bar" />
<Tar Path="c:\program files\tar" Include="All" />

In this example I need to receive the value:
c:\program files\tar


Following Alex' comment, It is also possible to do it within a powershell script.

I need to add this piece of code into an existing .cmd file, is it possible to call a powershell script from the .cmd and get the result back to the cmd?


PowerShell solution:

[xml]$xml = Get-Content $args[0]

VBScript solution:

Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.async = False
xml.load WScript.Arguments(0)

If xml.ParseError <> 0 Then
  WScript.Echo xml.ParseError.Reason
  WScript.Quit 1
End If

Set path = xml.SelectSingleNode("/Tar/Bar[@Path]")
WScript.Echo path.Value

Call the above scripts in your batch file like this:

powershell -File "C:\path\to\your.ps1" "C:\path\to\your.xml"

or like this:

cscript //NoLogo "C:\path\to\your.vbs" "C:\path\to\your.xml"

Both the PowerShell and the VBScript write the result to STDOUT. To assign that back to a batch variable you need a for loop like this (replace the ellipsis with one of the commands above):

for /f "tokens=*" %%p in ('...') do set pathvalue=%%p