Bhupesh Gautam
Bhupesh Gautam

Reputation: 11

powershell - How to find text in nested result

I have a script which will show all VMs in a host, how since this result is the output of RESTful API (JSON), the result is nested.

Output of the $Json variable -

{
    "ErrorAdditionalDetails":  null,
    "ErrorCode":  null,
    "ErrorMessage":  null,
    "Success":  true,
    "VirtualMachines":  [
                            {
                               "VirtualMachineName":  "xxxxxxxxxxx"
                            }
    ]
}

$json | Select-Object VirtualMachineName

The above command shows blank.

Result should be:

VirtualMachineName : xxxxxxxxxxx

Upvotes: -2

Views: 53

Answers (1)

mklement0
mklement0

Reputation: 437753

  • JSON is (structured) text, so in order to use OO techniques on it, you must first parse it into an object graph, which is what ConvertFrom-Json does.

  • You can then simply use dot notation (property access) to access the property of interest:

($json | ConvertFrom-Json).VirtualMachines

This will output the equivalent of [pscustomobject] @{ VirtualMachineName = "xxxxxxxxxxx" }, i.e. a [pscustomobject] instance with a .VirtualMachineName property containing the value of interest.

To output just the property value ("xxxxxxxxxxx"), simply append .VirtualMachineName to the command above.

Note:

  • The top-level .VirtualMachines property is an array.

  • The way PowerShell's member-access enumeration works is that if the array contains just one element, you'll get that element itself as output; with two or more elements, you'll get all elements as an array ([object[]]).

Upvotes: 0

Related Questions