Sunday, February 18, 2018

PowerShell nested functions won't affect variables in the outer scope

I recently converted a handful of PowerShell scripts to a single script file that defines several functions. I noticed that the script that used a helper function to do its job no longer worked; the nested function's changes to the variables created by the parent function weren't preserved outside the nested function. Previously I had been using $script:variableName in the inner function instead of $variableName, but since they were no longer script-scoped, that didn't help.

Some Googling turned up this Stack Overflow Q&A that suggested using Set-Variable to create the variables with the AllScope option. That appears to have worked. I can now do this to initialize them:

Set-Variable -Name someText, someBool, anotherBool -Option AllScope
$someText = ''
$someBool = $false
$anotherBool = $false

They can then be used in both the inner and outer functions without any special qualifiers.

No comments:

Post a Comment