Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only property names of PowerShell object

Tags:

powershell

I'm trying to print out only the property names of a Powershell object.
In a script I do an Invoke-RestMethod and Write-Host ($response.result | Format-List | Out-String) gives me a nice list of the $response.result object.
Get-Member -InputObject $response.result also does not display what I want.
$response.result looks something like this: @{id=1; skip=true}. How do I just get a list/table thats shows id, skip etc.
Many thanks!

like image 971
g_uint Avatar asked Jan 11 '17 14:01

g_uint


People also ask

How do I print the properties of an object in PowerShell?

Ideally your script would create your objects ( $obj = New-Object -TypeName psobject -Property @{'SomeProperty'='Test'} ) then just do a Write-Output $objects . You would pipe the output to Format-Table .

How do I get the property name of an object in PowerShell?

To get the object properties, the Get-member cmdlet is used in PowerShell. Specify a cmdlet, use the pipeline operator, and then type the Get-Member cmdlet to see all of the properties available from the specified command.

How do you select properties in PowerShell?

To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters. To select object properties, use the Property parameter.


3 Answers

If the result is just a simple 1-level hashtable, you could do something like:

(@{id=1; skip=$true}).GetEnumerator() | %{ $_.Key }

id
skip
like image 21
campbell.rw Avatar answered Oct 12 '22 22:10

campbell.rw


All PowerShell objects have a hidden property PSObject that allows accessing information about the object, e.g. its properties:

$response.result.PSObject.Properties | Select-Object -Expand Name
like image 90
Ansgar Wiechers Avatar answered Oct 12 '22 22:10

Ansgar Wiechers


If it's not a hashtable, you can use Get-Member to find the properties like this:

$response.result | Get-Member -MemberType Properties | Select-Object Name

like image 24
Mike Shepard Avatar answered Oct 13 '22 00:10

Mike Shepard