Purclot
Purclot

Reputation: 559

Add scriptmethod member

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?

Upvotes: 0

Views: 195

Answers (1)

iRon
iRon

Reputation: 23743

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

Upvotes: 1

Related Questions