Search code examples
powershellpowershell-4.0

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?


Solution

  • 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