Iterate over PSObject properties in PowerShell

I have this PSObject (from XML):

 bool : {IsActive, ShowOnB2C, ShowOnB2B, IsWebNews} str : {id, ProductId, GroupName, Unit...} int : {ProductIdNumeric, Prices_SalesOne, Prices_Treater, Prices_B2C...} arr : {EnvironmentBrands, Catalogs, NavisionLevels} long : long 

I would like to iterate over properties without using property names like bool .

I tried to index the object as follows:

 $document[0] 

But it does not give anything, but it also does not cause any errors.

Select-Object , but I have to use property names, and I don't want this.

 $documents | Select-Object bool,str 

ForEach does not ForEach over properties.

 $documents | ForEach { $_.name } 

returns doc, and this is the name of the tag (XML) containing bools, ints and strings.

+24
source share
4 answers

This is possible using the hidden PSObject property:

 $documents.PSObject.Properties | ForEach-Object { $_.Name $_.Value } 
+39
source

I prefer to use foreach to scroll 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 } 

Foreach-Object typically has better performance than Foreach-Object .

And yes, foreach is actually different from the Foreach-Object under the hood.

+6
source

As with stj , there is a Get-Member cmdlet with the -MemberType parameter you can use:

 $documents | Get-Member -MemberType Property | ForEach-Object { $_.Name } 
+3
source

You may also need NoteProperty with Get-Member.

 $documents | Get-Member -membertype property,noteproperty | Foreach name 

EDIT: clear all values:

 $obj = ls test.ps1 $obj | Get-Member -Type property | 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 
+3
source

All Articles