1

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.