Home > Back-end >  Add scriptmethod member
Add scriptmethod member

Time:12-06

this is an example from "the" book "Windows PowerShell in Action 3-edition", Bruce Payette, adding scriptmethod to an existing object and reverse itself, I've tried with PS 5 and PS 7:

$s = "hi world"
$sb = {
$a = [char[]] $this
[array]::reverse($a)
-join $a
}
$s | add-member -MemberType ScriptMethod -name Reverse -value $sb

There is no error message, but no method "Reverse" will be created as well?

CodePudding user response:

See: Example 3: Add a StringUse note property to a string

Because Add-Member can't add types to String input objects, you can specify the PassThru parameter to generate an output object.

$sb = {
    $a = [char[]] $this
    [array]::reverse($a)
    -join $a
}

$s = "hi world"
$s = $s | add-member -MemberType ScriptMethod -name Reverse -value $sb  -PassThru
$s.reverse()
dlrow ih
  • Related