- Courses
- đź’»Programming Languages
- 🪟PowerShell
- Scripting Fundamentals
- Control Flow
- Script Blocks and Scoping Rules
On this page
PowerShell Script Blocks and Variable Scope
Published on June 10, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A script block is a reusable, storable unit of executable PowerShell code enclosed in curly braces. Scope determines where variables are visible, how long they live, and which parts of a script can read or modify them. Understanding both concepts together is what separates scripts that behave predictably from scripts that produce mysterious, hard-to-debug results.
What Is a Script Block?​
A script block is a collection of statements enclosed in {}. Syntactically it is an instance of System.Management.Automation.ScriptBlock — a .NET object that can be stored in a variable, passed as a parameter, returned from a function, and executed on demand.
{ "Hello from a script block" }
On its own, this expression evaluates to a ScriptBlock object and produces no output. Nothing runs until the block is explicitly executed.
Important distinction: Not every pair of braces in PowerShell is a script block. The body of an
ifstatement, aforloop, aforeachloop, and aswitchstatement are statement blocks — they execute immediately as part of the control flow construct and do not create a new scope for variables. Only aScriptBlockcreates a new child scope.
# Statement block — NOT a script block, does NOT create a new scope
if ($true) {
$x = 10 # $x is visible outside this if block
}
$x # 10 — still accessible
# Script block — creates a new scope
& {
$y = 10 # $y is local to this script block
}
$y # nothing — $y does not exist here
Executing Script Blocks​
The call operator &​
The & (call) operator executes a script block in a child scope — a new scope that inherits from the caller's scope but whose local variables do not affect the caller:
$block = { "Running the block" }
& $block
# Output: Running the block
Store the output in a variable:
$block = { 1 + 1 }
$result = & $block
$result # 2
Dot-sourcing: running in the caller's scope​
The dot-source operator . runs a script block in the current scope rather than a child scope. Variables defined inside the block become variables in the caller's scope:
$x = 1
. {
$x = 99 # modifies the CALLER's $x, not a local copy
$new = "created"
}
$x # 99 — modified by the dot-sourced block
$new # "created" — now exists in caller's scope
Dot-sourcing is how script files are loaded into the current scope (Import-Module and . .\myscript.ps1 both use this mechanism). Use it deliberately; using it accidentally is a common source of unexpected variable pollution.
Invoke-Command​
Invoke-Command -ScriptBlock is the primary mechanism for running script blocks, both locally and on remote computers:
# Run locally
Invoke-Command -ScriptBlock { Get-Process | Select-Object -First 3 }
# Pass arguments with -ArgumentList
Invoke-Command -ScriptBlock {
param($p1, $p2)
"First: $p1, Second: $p2"
} -ArgumentList "Alpha", "Beta"
# Output: First: Alpha, Second: Beta
Script Block Parameters​
Script blocks accept parameters using the param() keyword, with full type annotation support:
$greet = {
param(
[string]$Name,
[int]$Age
)
"Hello, $Name. You are $Age years old."
}
& $greet "Alice" 30
# Output: Hello, Alice. You are 30 years old.
Parameters can also be called by name when using the call operator:
$greet = {
param($p1, $p2)
"p1: $p1, p2: $p2"
}
& $greet -p2 "Second" -p1 "First"
# Output: p1: First, p2: Second
Script Blocks in Pipelines​
Script blocks are the mechanism behind Where-Object, ForEach-Object, Sort-Object calculated properties, and Select-Object calculated properties. Inside these pipeline blocks, $_ (or $PSItem) represents the current pipeline object:
# Where-Object — runs once per input object, passes those where block returns $true
1..10 | Where-Object { $_ -gt 5 }
# ForEach-Object — runs once per input object
"red","green","blue" | ForEach-Object { "Color: $_" }
# Calculated property in Select-Object
Get-Process | Select-Object Name, @{ Name = "MemMB"; Expression = { [math]::Round($_.WorkingSet64 / 1MB, 1) } }
Delay-Bind Script Blocks​
A delay-bind scriptblock passes a script block as the argument to a typed parameter that accepts pipeline input. PowerShell evaluates the script block for each piped object, using $_ to represent the current object:
# Without delay-binding — ForEach-Object required
Get-ChildItem *.log | ForEach-Object { Rename-Item -Path $_ -NewName "old_$($_.Name)" }
# With delay-binding — cleaner, same result
Get-ChildItem *.log | Rename-Item -NewName { "old_$($_.Name)" }
Requirements for delay-bind scriptblocks:
- The target parameter must be typed (not
[object]or[scriptblock]) - The target parameter must accept pipeline input
- Pipeline input must be provided — delay-bind fails without it
# This fails — no pipeline input provided
Rename-Item -NewName { $_.Name + ".old" }
# Error: Cannot evaluate parameter 'NewName' because its argument is
# specified as a scriptblock and there is no input.
The return Keyword in Script Blocks​
return exits a script block at that line. It does not suppress output produced before the return — all previous output is still emitted:
$block = {
"Line 1" # emitted
"Line 2" # emitted
return "Done" # "Done" is emitted, then block exits
"Line 4" # never reached
}
& $block
# Output:
# Line 1
# Line 2
# Done
Variable Scope​
Scope is the boundary within which a variable is visible and writable. PowerShell creates a new child scope whenever a script block or function is invoked with & or called directly. The child scope inherits a read-only view of the parent's variables — it can read them but creating a same-named variable in the child creates a local copy that shadows the parent's variable without modifying it.
$x = 5
& {
Write-Output $x # reads parent's $x — output: 5
$x = 99 # creates a LOCAL $x — does NOT modify parent
Write-Output $x # output: 99
}
Write-Output $x # still 5 — parent is unchanged
The Four Primary Scopes​
Local scope​
The innermost active scope. Variables created in a function or script block are local by default. They disappear when the scope ends:
function Test-Local {
$localVar = "I am local"
Write-Output $localVar
}
Test-Local
$localVar # nothing — does not exist outside the function
Script scope​
The scope of the .ps1 script file currently running. Variables at the top level of a script are in script scope. Functions defined in the same script can read these variables:
# In a .ps1 file
$script:config = "production"
function Get-Config {
$script:config # reads the script-level variable
}
Get-Config # output: production
Global scope​
The top-level session scope. Variables created here persist for the entire session and are visible everywhere:
$global:counter = 0
function Increment {
$global:counter++
}
Increment
Increment
$global:counter # 2
Use global scope sparingly. A function that modifies a global variable is harder to test, harder to reuse, and harder to reason about than one that accepts inputs and returns outputs.
Private scope​
A variable declared with the private: modifier is visible in its own scope but is not inherited by child scopes. This prevents functions called from the current scope from accidentally reading the variable:
$private:secret = "sensitive-data"
function Try-Read {
$secret # nothing — private variable is not inherited
}
Try-Read # no output
$private:secret # "sensitive-data" — visible in own scope
Scope Modifiers​
Scope modifiers prefix a variable name with the scope and a colon to explicitly target a specific scope regardless of the current context:
ModifierTargets$global:nameThe top-level session scope$script:nameThe enclosing .ps1 script scope$local:nameThe current scope explicitly$private:nameThe current scope, hidden from child scopes$using:nameA parent scope variable in parallel or remote contexts
$x = 1
function Modify-Parent {
$script:x = 99 # writes to the script scope, not local
}
Modify-Parent
$x # 99
The $using: Scope Modifier​
The $using: modifier is essential for passing variables into script blocks that execute in a separate scope that has no inheritance relationship with the caller — specifically Start-Job, Invoke-Command -ComputerName, and ForEach-Object -Parallel.
Regular variable reference does not work in these contexts because the child scope is in a completely separate runspace:
$threshold = 100
# WRONG — $threshold is not in scope inside Start-Job
$job = Start-Job { Get-Process | Where-Object CPU -gt $threshold }
Receive-Job $job # nothing — $threshold is $null inside the job
# CORRECT — $using: captures the value at submission time
$job = Start-Job { Get-Process | Where-Object CPU -gt $using:threshold }
Receive-Job $job # works correctly
The serialization caveat​
When $using: passes a variable to a remote or parallel scope, the value is serialized (converted to XML) at submission time and deserialized on the receiving end. This means:
- The remote scope receives a snapshot of the value — not a live reference
- Complex objects like
[System.IO.FileInfo]and custom classes lose their methods — only their properties survive deserialization - Primitive types (
int,string,bool, arrays, hashtables) round-trip correctly - Changes to the object inside the job do not affect the original variable
$list = [System.Collections.Generic.List[int]]@(1,2,3)
$job = Start-Job {
$using:list.GetType().FullName # Deserialized.System.Collections.Generic.List`1[[...]]
$using:list.Add(4) # This FAILS — Add() method is gone after deserialization
}
Use simple types with $using:. When complex objects are needed, pass their data (arrays, hashtables, property values) rather than the full object.
The AllScope Option​
AllScope is a variable option that makes a variable visible across all scopes — child scopes see and modify the same variable rather than getting a local copy:
# Create a variable with the AllScope option
New-Variable -Name SharedCounter -Value 0 -Option AllScope
function Increment {
$SharedCounter++ # modifies the original, not a local copy
}
Increment
Increment
$SharedCounter # 2 — modified by the function
AllScope is rarely the right design. It makes variable access implicit and makes code harder to reason about. Prefer passing values as parameters and returning results explicitly. The one legitimate use case is constants or lookup tables that many functions need to read (but not write).
begin, process, and end in Script Blocks​
Script blocks — like functions — can include begin, process, and end blocks for pipeline-aware behaviour. This is particularly useful when storing pipeline-processing logic in a variable:
$accumulator = {
begin {
$total = 0
$count = 0
}
process {
$total += $_
$count++
}
end {
[PSCustomObject]@{
Count = $count
Total = $total
Average = if ($count -gt 0) { $total / $count } else { 0 }
}
}
}
1..10 | ForEach-Object $accumulator
# Count: 10, Total: 55, Average: 5.5
Scope Behaviour Summary​
ConstructCreates new scope?Inherits parent variables?& { } (call operator)YesYes (read-only copy). { } (dot-source)NoYes (fully shared)Function callYesYes (read-only copy)if / for / foreach statementNoYes (fully shared)Start-Job scriptblockYes (separate runspace)No — use $using:``Invoke-Command -ComputerNameYes (remote runspace)No — use $using:``ForEach-Object -ParallelYes (separate runspace)No — use $using:
Common Mistakes to Avoid​
Assuming if and for blocks create their own scope. They do not. A variable created inside an if block is visible in the same scope where the if statement appears.
Modifying parent-scope variables without explicit modifiers. Assigning to a variable inside a function creates a local copy. Use $script:varname or $global:varname when the intent is to modify an outer scope, and document why.
Using global variables instead of parameters. A function that reads $global:config cannot be tested in isolation, cannot be reused in a different context, and cannot be composed with other functions cleanly. Pass configuration as a parameter.
Forgetting $using: in parallel and remote scriptblocks. Regular variable references silently resolve to $null inside Start-Job, Invoke-Command -ComputerName, and ForEach-Object -Parallel. Always use $using:varname to pass variables into these contexts.
Expecting $using: to pass live references. Variables are serialized at submission time. Changes inside the job or remote session do not propagate back. Complex objects lose their methods after deserialization.
Dot-sourcing unintentionally. Using . .\script.ps1 runs the script in the current scope, importing all its variables and functions. This is sometimes desirable (loading a library) and sometimes unexpected (polluting the current scope with internal variables).
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Loops
Next
Functions and Modular Code
-
What Is a Script Block?
-
Executing Script Blocks
- The call operator
& - Dot-sourcing: running in the caller's scope
Invoke-Command
- The call operator
-
Script Block Parameters
-
Script Blocks in Pipelines
-
Delay-Bind Script Blocks
-
The
returnKeyword in Script Blocks -
Variable Scope
-
The Four Primary Scopes
- Local scope
- Script scope
- Global scope
- Private scope
-
Scope Modifiers
-
The
$using:Scope Modifier- The serialization caveat
-
The
AllScopeOption -
begin,process, andendin Script Blocks -
Scope Behaviour Summary
-
Common Mistakes to Avoid
