How to loop through the Properties of a PowerShell Object

If you have want to iterate through a hashtable to make use of the key/value pairs, you can do that using the GetEnumerator() function and foreach.

1
2
3
4
5
6
7
8
9
10
11
12
# Preparing the hastable
$myHastable = @{
    "AnimalType" = "Dog"
    "Name" = "Bella"
    "Owner" = "Mr. Smith"
}
 
# Looping through the hastable
$myHastable.GetEnumerator() | foreach { 
    $_.Name
    $_.Value
}

To access the values of a PowerShell object you have to know the name of the object property to access it, which looks like this: $myObject.PropertyName

I had to make use of all the properties of a PowerShell object without knowing its property names beforehand. Since GetEnumerator() does not work on objects I had to come up with another solution, which is to access the properties using the PSMemberSet of my custom object.

1
2
3
4
5
6
7
8
9
10
11
12
# Preparing the object
$myObject = New-ObjectType PSObject
$myObject | Add-MemberType NoteProperty –Name "AnimalType" –Value "Dog"
$myObject | Add-MemberType NoteProperty –Name "Name" –Value "Bella"
$myObject | Add-MemberType NoteProperty –Name "Owner" –Value "Mr. Smith"
 
 
# Looping through the object
$myObject.PSObject.Properties | foreach { 
    $_.Name
    $_.Value
}

Works as easy as if it were a hastable.

Leave a Reply

Your email address will not be published. Required fields are marked *