Search code examples
powershellpowershell-3.0

How to find all the scriptmethod in an object and call it?


In an object multiple scriptmethod present.

function new-obj {
$Obj = [pscustomobject]@{

    Data1 = 'value1'
    Data2 = 'value2'

}

$Obj | Add-Member -MemberType ScriptMethod -Name DoSomethingWithData1 -Value { <# Code using Data1 #> }
$Obj | Add-Member -MemberType ScriptMethod -Name DoSomethingWithData2 -Value { <# Code using Data2 #> }

$obj
}

$o = New-obj 
$o.DoSomethingWithData1()
$o.DoSomethingWithData2()

I would like to know all the scriptmethod and call them one by one (via foreach). Is there any way to find all the scriptmethod for an object and invoke them?


Solution

  • Either use Get-Member:

    Get-Member -InputObject $o -MemberType ScriptMethod |ForEach-Object {
        $o.$($_.Name).Invoke()
    }
    

    or access them through the psobject memberset:

    $o.psobject.Methods |Where {$_ -is [psscriptmethod]} |ForEach-Object Invoke