user3469799
user3469799

Reputation: 219

Iterate over static properties of a class

To access a static method, we use

[namespace.ClassName]::MethodName()

and for static properties we use

[namespace.ClassName]::Property

How do I iterate through all the static properties inside this class?

$list = [namespace.ClassName] | Get-Member -Static -MemberType Property

Returns me a list of all the static properties, but how do I use it, i.e access its value. If I want to pass the variable to a method, how do I do so? $list[0] does not work.

Upvotes: 5

Views: 645

Answers (2)

OldFart
OldFart

Reputation: 2479

This is essentially the same as the answer by Ryan Bemrose, but written as a function that spits out objects.

function Get-StaticProperties
{
    Param (
        [type]$Class
    )

    gm -InputObject $Class -Static -MemberType Property |
        select -ExpandProperty Name | foreach {
            New-Object PSObject -Property ([ordered]@{ Name=$_; Value=$Class::$_ })
        }
}

Then, to invoke it:

PS> Get-StaticProperties System.Math

Name            Value
----            -----
E    2.71828182845905
PI   3.14159265358979

Upvotes: 3

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

This should work with a foreach loop over the Name property.

$class = [namespace.ClassName] 
$list = $class | Get-Member -Static -MemberType Property
$list | select -expand Name | foreach {
   "$_ = $($class::$_)"
}

Note that you can iterate over classes if needed by changing the $class variable.

Using the [Math] class for an example:

PS> $class = [math]
PS> $class | Get-Member -Static -MemberType Property | select -expand Name | foreach { "$_ = $($class::$_)" }
E = 2.71828182845905
PI = 3.14159265358979

Upvotes: 6

Related Questions