Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify parent scope variable using Powershell

Tags:

powershell

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?

like image 808
C Johnson Avatar asked Jul 20 '11 18:07

C Johnson


People also ask

Does PowerShell have variable scope?

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.

What does $_ mean in PowerShell?

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.

Can PowerShell function access global variable?

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.


2 Answers

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

like image 68
Shay Levy Avatar answered Sep 22 '22 06:09

Shay Levy


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     } } 
like image 45
Nick W. Avatar answered Sep 21 '22 06:09

Nick W.