I am trying to print the key value pair from Data Object type XML using a Powershell script.
<?xml version="1.0"?>
<Objects>
<Object Type="System.Management.Automation.PSCustomObject">
<Property Name="Display" Type="System.String">Microsoft</Property>
<Property Name="Service" Type="Microsoft.Management.Service">Database</Property>
</Object>
<Object Type="System.Management.Automation.PSCustomObject">
<Property Name="Display" Type="System.String">Microsoft</Property>
<Property Name="Service" Type="Microsoft.Management.Service">RPC</Property>
</Object>
</Objects>
Here is the script used.
[xml]$file = Get-Content C:\xml-report.xml
foreach ($obj in $file.Objects.Object) {
echo $obj.Display;
echo $obj.Service;
}
How should I iterate through each key (Display, Service) and print only the values of those- ie
Microsoft
Database
Microsoft
RPC
The output which I get now is as below. Could someone help me here?
Object
Object
Object
As you are trying to explicitly access the properties with name Service
and Display
, here is a solution to directly access those, in case your xml file contains more elements you're not concerned with:
foreach ($obj in $file.Objects.Object.Property) {
if('Display','Service' -contains $obj.Name) {
write-output $obj.'#text'
}
}
Or in one line:
$file.Objects.Object.Property | ? { 'Display','Service' -contains $_.name } | Select '#text'
You were just omitting the Property element. Your loop would work with a slight modification:
[xml]$file = Get-Content "C:\temp\xml-report.xml"
foreach ($obj in $file.Objects.Object)
{
$obj.Property | % { $_.'#text' }
}
If you are using Powershell version 3 or above you could try use this:
[xml]$file = Get-Content C:\xml-report.xml
$file.Objects.Object.Property.'#text'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.