5

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user3469799
  • 219
  • 1
  • 3
  • 12

2 Answers2

6

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
Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54
3

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
OldFart
  • 2,411
  • 15
  • 20