I'm fairly new to powershell, and I'm just not getting how to modify a variable in a parent scope:
$val = 0 function foo() { $val = 10 } foo write "The number is: $val"
When I run it I get:
The number is: 0
I would like it to be 10. But powershell is creating a new variable that hides the one in the parent scope.
I've tried these, with no success (as per the documentation):
$script:$val = 10 $global:$val = 10 $script:$val = 10
But these don't even 'compile' so to speak. What am I missing?
PowerShell ScopesVariables and functions that are present when PowerShell starts have been created in the global scope, such as automatic variables and preference variables. The variables, aliases, and functions in your PowerShell profiles are also created in the global scope.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
Thus, a PowerShell global variable is one that is available throughout the program and can be accessed anywhere. You can set its value in many ways and can create it with many characteristics such as a private global variable, read-only, constant, and more.
You don't need to use the global scope. A variable with the same name could have been already exist in the shell console and you may update it instead. Use the script scope modifier. When using a scope modifier you don't include the $ sign in the variable name.
$script:val=10
I know this is crazy old but I had a similar question and found this post in my search and wanted to share the answer I found:
$val = 0 function foo { Set-Variable -scope 1 -Name "Val" -Value "10" } foo write "The number is: $val"
More information can be found in the Microsoft Docs article About Scopes.
Be aware that recursive functions require the scope to be adjusted accordingly:
$val = ,0 function foo { $b = $val.Count Set-Variable -Name 'val' -Value ($val + ,$b) -Scope $b if ($b -lt 10) { foo } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With