Compartilhar via


PowerShell - Referencing variable in current scope

PowerShell allows creating variables dynamically without declaring. During assignment, it also creates new variables in the inner scope (unlike programming languages, where there is only one instance of the variable).

The following examples will make it clear on scoping rule

 Save the following script into a file ScopeTest1.ps1
  $myvar = "Hello World"<br>function PrintHelloWorld <br>{ <br>  $myvar = "Hello Universe"<br>  Write-Host "$myvar"<br>} <br>Write-Host "$myvar" <br>PrintHelloWorld <br>Write-Host "$myvar" 

PS C:\PowerShellExamples> .\ScopeTest1.ps1
Hello World
Hello Universe
Hello World
 Now save the following script into a file ScopeTest2.ps1
  $myvar = "Hello World"<br>function PrintHelloWorld <br>{ <br>  ([ref]$myvar).Value = "Hello Universe"    Write-Host "$myvar" <br>} <br>Write-Host "$myvar" <br>PrintHelloWorld <br>Write-Host "$myvar" 

PS C:\PowerShellExamples> .\ScopeTest2.ps1
Hello World
Hello Universe
Hello Universe

In ScopeTest2.ps1, a new $myvar is not created in function scope. Existing variable is referenced and updated