'Retrieve elements from PSCustomObject in Powershell
I am new to Powershell and is currently facing this problem.
I call a REST API in Powershell which stores the API response in $GetResponse variable. Hereby some display statements:-
Write-Host $Getresponse.GetType()
Output :- System.Management.Automation.PSCustomObject
Write-Host $Getresponse.registered_models.name
Output :- test test1
Write-Host $Getresponse | Get-Member -Force
Output:- @{registered_models=System.Object[]}
I want to store the output of $Getresponse into an array variable but couldn't figure out a way to do it.
Solution 1:[1]
Note:
Write-Hostis typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it by itself; e.g.,$valueinstead ofWrite-Host $value(or useWrite-Output $value, though that is rarely needed); see this answer.Also note that
Write-Host, because it uses simple.ToString()stringification instead of PowerShell's rich output formatting system, typically produces unhelpful representations of complex objects; to output to the display only while still getting rich output formatting, pipe to theOut-Hostcmdlet instead.Even the rich default output formatting can be insufficient for deeply nested, such as object graphs that are constructed (automatically, by
Invoke-RestMethod) from JSON responses received from REST services, for instance. To quickly visualize the structure of such object graphs, you can convert them back to JSON, by piping them toConvertTo-Json- be sure to specify a sufficient-Depth, for the reasons explained in this post.
Based on the sample of the formatted output you posted in a comment, you were looking for the nested .name property values, which you can obtain via member-access enumeration.
[array] $names = $Getresponse.registered_models.name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
