Tengiz
Tengiz

Reputation: 8429

PowerShell Add-Member ScriptMethod - cannot set variable value

I'm trying to set the variable value inside the script method which I try to attach to an object using Add-Member. What am I doing wrong?

$a = "old value";
$obj = New-Object -TypeName "System.Object"
Add-Member -InputObject $obj -Name Info -Value { param($msg) $a = $msg; } -MemberType ScriptMethod
$obj.Info("123");
Write-Host "a = $a";

I expected output to be a = 123 but I see a = old value. I think the issue is related to scoping (inside the script method, $a must mean a different variable since the value is not maintained). How do I set the value of the $a variable that I already have?

Upvotes: 1

Views: 976

Answers (1)

Theo
Theo

Reputation: 61148

You're right about the Scoping.

If you make $a a global $global:a or give it a script scope $script:a the below works:

$script:a = "old value"
$obj = New-Object -TypeName "System.Object"
Add-Member -InputObject $obj -Name Info -Value { param($msg) $script:a = $msg; } -MemberType ScriptMethod
$obj.Info("123")

Write-Host "a = $script:a"

Output:

a = 123

Upvotes: 3

Related Questions