Your First Script
Prerequisites: Loops
A script is a text file with a .ps1 extension containing PowerShell
commands.
Writing and running a script
Create hello.ps1:
# illustrative
# hello.ps1 — my first script
$name = $env:USERNAME ?? $env:USER
Write-Output "Hello, $name!"
Write-Output "Today is $((Get-Date).DayOfWeek)."
Run it by path from the terminal:
PS C:\scripts> .\hello.ps1
Hello, ada!
Today is Tuesday.
The .\ means "in the current folder" — like Bash, PowerShell doesn't run
scripts from the current folder by name alone, for security.
Execution policy (Windows)
On Windows, the execution policy may block scripts:
.\hello.ps1 : File C:\scripts\hello.ps1 cannot be loaded because running scripts is disabled on this system.
Allow your own scripts (and signed downloaded ones) for your user account:
# illustrative
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
RemoteSigned— scripts you wrote run; scripts downloaded from the internet must be signed (or unblocked withUnblock-File). It's the default on Windows Server and a sensible choice for workstations.- The execution policy is a safety feature against accidents, not a security boundary.
- On Linux and macOS, there's no execution policy.
Running on Linux and macOS
Add a shebang line to run a script directly:
# illustrative
#!/usr/bin/env pwsh
Write-Output "Hello from PowerShell on Linux"
Then chmod +x hello.ps1 and ./hello.ps1.
Dot-sourcing
Running a script normally keeps its variables and functions to itself.
Dot-sourcing it (. .\helpers.ps1, with a dot and a space) runs it in
the current scope, so its functions stay available — a simple way to load
helper functions.
Common mistakes
- Double-clicking a
.ps1file on Windows opens it in Notepad, by design. Run scripts from a terminal. - Setting the execution policy to
UnrestrictedorBypassglobally to "fix" errors.RemoteSignedfor the current user is enough.