PowerShell Scripts & Scopes
A script is a text file with the .ps1 extension containing PowerShell code. Scripts let you save and share your automation. This lesson shows how to write and run them, how they receive parameters, and how scopes decide which variables each piece of code can see.
Writing and running a script
The examples on this site are scripts: the code is saved as /w/main.ps1 and run with pwsh -File. Here a script creates a second script and runs it:
Set-Content ./hello.ps1 @'
param([string]$Name = 'world')
"Hello, $Name! (from $(Split-Path -Leaf $PSCommandPath))"
'@
& ./hello.ps1
& ./hello.ps1 -Name Ada
./hello.ps1 GraceHello, world! (from hello.ps1)
Hello, Ada! (from hello.ps1)
Hello, Grace! (from hello.ps1)
To run a script in the current folder you must write its path (./hello.ps1), not just hello.ps1. PowerShell doesn't search the current folder by default, a protection against planted scripts. From another shell, run a script with pwsh -File ./hello.ps1 -Name Ada.
Execution policy (Windows)
On Windows, an execution policy controls whether scripts may run at all. The default on Windows clients is Restricted in Windows PowerShell and RemoteSigned in PowerShell 7. On Linux and macOS, execution policy is not enforced (Unrestricted).
PS C:\> Get-ExecutionPolicy
RemoteSigned
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
PS C:\> Unblock-File .\downloaded-script.ps1 # remove the "from the internet" mark| Policy | Allows |
|---|---|
Restricted |
no scripts, only interactive commands |
AllSigned |
only scripts signed by a trusted publisher |
RemoteSigned |
local scripts; downloaded scripts must be signed |
Unrestricted / Bypass |
everything (Bypass doesn't even warn) |
Execution policy is a safety belt against accidents, not a security boundary.
Script parameters and automatic variables
A script's param() block must be the first statement in the file (after comments and #Requires lines). Scripts also get some useful automatic variables:
| Variable | Contains |
|---|---|
$PSScriptRoot |
folder of the running script |
$PSCommandPath |
full path of the running script |
$args |
arguments not bound to a parameter |
$LASTEXITCODE |
exit code of the last native program or script |
"Script folder: $PSScriptRoot"
"Script file: $(Split-Path -Leaf $PSCommandPath)"
Set-Content ./check.ps1 @'
param([int]$Threshold)
if ($Threshold -gt 90) { exit 2 }
exit 0
'@
& ./check.ps1 -Threshold 95
"exit code: $LASTEXITCODE"
& ./check.ps1 -Threshold 10
"exit code: $LASTEXITCODE"Script folder: /w
Script file: main.ps1
exit code: 2
exit code: 0
Use $PSScriptRoot to find files that ship next to your script (Join-Path $PSScriptRoot 'config.json'), so the script works no matter which folder it's started from. exit <n> ends a script with an exit code that schedulers and CI systems can check.
Scopes
PowerShell keeps variables in nested scopes. Each script, function and script block gets its own child scope. Code can read variables from parent scopes, but assigning creates a new local variable unless you name another scope:
$level = 'script'
function Show-Scope {
"inside, before: $level" # reads the parent's variable
$level = 'function' # creates a local variable
"inside, after: $level"
}
Show-Scope
"outside: $level"inside, before: script
inside, after: function
outside: script
Scope modifiers
Prefix a variable with a scope name to reach outside the current scope:
| Modifier | Meaning |
|---|---|
$local:x |
the current scope (default for assignments) |
$script:x |
the scope of the script file |
$global:x |
the session, visible everywhere (avoid) |
$private:x |
visible only in the current scope, not in children |
$using:x |
a local value sent to a remote/parallel/job script block |
$script:callCount = 0
function Register-Call {
$script:callCount++
}
1..3 | ForEach-Object { Register-Call }
"Calls: $callCount"
$private:secret = 'hidden'
function Read-Secret { "child sees: [$secret]" }
Read-SecretCalls: 3
child sees: []
Modifying $script: variables is fine for small counters and caches, but prefer passing values in through parameters and out through output.
Dot-sourcing a script
Running a script with & executes it in a child scope: its functions vanish when it ends. Dot-sourcing (. ./file.ps1) runs it in your scope instead, which is how you load a library of helper functions:
Set-Content ./helpers.ps1 @'
function Get-Double($n) { $n * 2 }
$helperVersion = '1.2'
'@
& ./helpers.ps1
"After &: $([bool](Get-Command Get-Double -ErrorAction SilentlyContinue))"
. ./helpers.ps1
"After dot-source: $(Get-Double 21), version $helperVersion"After &: False
After dot-source: 42, version 1.2
For bigger libraries, a module (next lesson) is the better tool.
Tip: Start scripts with
#Requires -Version 7.2to fail fast on older PowerShell versions, andSet-StrictMode -Version Latestto catch typos early.
Test yourself
How do you run deploy.ps1 from the current folder?
- deploy.ps1
- ./deploy.ps1
- run deploy.ps1
- call deploy
Inside a function, $total = 5 runs while the script also has $total = 1. What is the script's $total afterwards?
- 5
- 1
- 6
- $null
Which variable gives the folder of the running script?
- $PWD
- $HOME
- $PSScriptRoot
- $PSHOME