Gobikannan Gobikannan - 3 months ago 8
PowerShell Question

Get property value by passing property name from XML

How to get property value by passing property name from XML file using PowerShell. For example, The following is the XML file content

<?xml version="1.0" encoding="utf-8"?>
<MyProject>
<!-- My Comment Here -->
<MyPropertyGroup>
<PropertyID>2</PropertyID>
<PropertyName>ItsMyName</PropertyName>
</MyPropertyGroup>
<MyPropertyGroup>
<MobileNo>3</MobileNo>
<NickName>ItsMyNickName</NickName>
</MyPropertyGroup>
</MyProject>


I tried like below:

[xml]$file = Get-Content 'C:\Temp\MyTest.xml'
$file.ChildNodes[1].GetElementsByTagName("PropertyName")


But it return result as like:

#text
-----
ItsMyName


I want to get
ItsMyName
as result to store into variable.

Answer

You can expand the property like this

$file.ChildNodes[1].GetElementsByTagName("PropertyName")."#text"

Or to be able to accept multiples results you could pipe it to Select-Object like this

$file.ChildNodes[1].GetElementsByTagName("PropertyName") | Select-Object -ExpandProperty "#text"