Scope
Prerequisites: Functions
Scope decides where a variable is visible.
$color = 'blue'
function Show-Color {
"Inside, before: $color"
$color = 'red'
"Inside, after: $color"
}
Show-Color
"Outside: $color"
Inside, before: blue
Inside, after: red
Outside: blue
- A function can read variables from its parent scope.
- Assigning creates a new, local variable — the outer
$coloris untouched.
That's deliberate: functions can't accidentally change the caller's variables.
Scope modifiers
$count = 0
function Add-One { $script:count++ }
Add-One
Add-One
$count
2
| Modifier | Means |
|---|---|
$local:x |
the current scope (the default) |
$script:x |
the script file's scope |
$global:x |
the session-wide scope |
$using:x |
a local variable inside a remote or parallel block (Level 3) |
Better: pass in, return out
Modifying $script: variables works, but functions are easier to reuse
and test when they take input through parameters and return results:
function Add-One { param([int]$Value) $Value + 1 }
$count = 0
$count = Add-One $count
$count = Add-One $count
$count
2
Avoid $global: in scripts altogether — it leaks into the user's
session.