How to use Select-Xml cmdlet to parse XML from external source?

86 Views Asked by At

I'm trying to use Select-Xml to parse XML from SQL server. I have a sql query which gives me an XML string ($Query) and I want to sum up all "Users" values from this XML.

My script works perfectly if I use external file for "-Path". But I don't know how to use put XML string into "-Path".

If I run Write-Host $path i'm getting just a "System.Data.DataRow" message

If I run echo $path i'm getting XML string.

$XPath = "//Users" # XML element
$total = 0 # Counter to sum up all Users elements

$Query = "SELECT [LicXML] FROM [SQLSERVER].[dbo].[Conf] WHERE Name='Lic'" # Query to get XML string
$path = Invoke-Sqlcmd -Query $Query -ServerInstance 'SQLSERVER' -Database SQLDB # Request to MSSQL

Select-Xml -Path $path -XPath $Xpath | ForEach-Object { $total += [int] $_.node.InnerXML }; # Parsing
Write-Host "total:" $total # Users sum

I tried different ways but still have no idea. Could you help me please?

Screenshot of the result

UPD. I'm too dumb for this place. Firstly, I must use -Content flag instead of -Path But still dont' know how to put my XML string to the -Content

UPD2. I believe I can use $path = $path | Out-String to push the XML string in my variable. But now I have other problem - how to cut off the header of the query result? Because it's not a valid XML until the header is presented:

Select-Xml : Cannot convert value "
LicXML                                                                                                                                                    
-------                                                                                                                                                    
<License ProductID="ICE"><Data Version="1.0" AuthenticationKeyID="PCApps">...
" to type "System.Xml.XmlDocument"
1

There are 1 best solutions below

0
On

Finally:

$XPath = "//Users" #XML Value to find
$total = 0 #Counter to sum up Users
$Query = "SELECT [LicXML] FROM [SQLSERVER].[dbo].[Conf] WHERE Name='Lic'" #Query to gather raw XML string
$path = Invoke-Sqlcmd -Query $Query -ServerInstance SQLSERVER #Sending a query
$path["LicXML"] | Select-Xml -XPath $Xpath | ForEach-Object { $total += [int] $_.node.InnerXML }; #Black magic, XML parsing and counting a sum