The concept of scope
PowerShell uses the concept of scope to protect variables, functions, PSDrives, and aliases from inadvertent change by limiting how they may be accessed and modified. Let’s demonstrate:
- Create a variable and set its value:
$ScopeTest = 10
- Create a function:
Function Set-ScopeTest {$ScopeTest = 15; Write-Output "the value of ScopeTest is $ScopeTest"}
- Test the value of
$ScopeTest
by calling the variable:$ScopeTest
- Run our function:
Set-ScopeTest
- We can see from the output that the value of
$ScopeTest
inside the function is15
. Let’s check whether the value has changed permanently:$ScopeTest
No, it hasn’t. That’s because the function is operating on its local scope; it can read the value of the variable, and it can change it while it’s running, but it can’t change it permanently because the variable exists outside the function. This is known as the scope of the function.
PowerShell has the following...