Iterate over PSObject properties in PowerShell
This is possible using the hidden property PSObject
:
$documents.PSObject.Properties | ForEach-Object {
$_.Name
$_.Value
}
This won't work with certain PowerShell-created objects (PSObject
s) that contain "NoteProperties" (properties of type NoteProperty
).
See this answer for a method that covers all property types.
You might need NoteProperty too with Get-Member.
$documents | Get-Member -membertype property,noteproperty |
Foreach name
EDIT: type "properties" seems a more generic catchall
$documents | get-member -type properties | % name
EDIT: dump out all the values:
$obj = ls test.ps1
$obj | Get-Member -Type properties | foreach name |
foreach { $_ + ' = ' + $obj.$_ }
Attributes = Normal
CreationTime = 06/01/2019 11:29:03
CreationTimeUtc = 06/01/2019 15:29:03
Directory = /Users/js
DirectoryName = /Users/js
Exists = True
Extension = .ps1
FullName = /Users/js/test.ps1
IsReadOnly = False
LastAccessTime = 06/05/2019 23:19:01
LastAccessTimeUtc = 06/06/2019 03:19:01
LastWriteTime = 06/01/2019 11:29:03
LastWriteTimeUtc = 06/01/2019 15:29:03
Length = 55
Name = test.ps1
An alternative way without "| foreach name", that needs extra parentheses:
$obj | Get-Member -Type properties |
foreach { $_.name + ' = ' + $obj.($_.name) }
Another take which results in an array that's easier to work with, and might be good for objects converted from json:
$a = '{ prop1:1, prop2:2, prop3:3 }' | convertfrom-json
$a
prop1 prop2 prop3
----- ----- -----
1 2 3
$a.PSObject.Properties | select name,value
name value
---- -----
prop1 1
prop2 2
prop3 3
I prefer using foreach
to loop through PowerShell objects:
foreach($object_properties in $obj.PsObject.Properties)
{
# Access the name of the property
$object_properties.Name
# Access the value of the property
$object_properties.Value
}
Generally, foreach
has higher performance than Foreach-Object
.
And yes, foreach
is actually different than Foreach-Object
under the hood.