Functions and Scripts
Write reusable functions with validated parameters, save scripts as .ps1 files, and handle errors.
What You'll Learn
- Writing functions with param blocks and CmdletBinding
- Parameter validation (Mandatory, ValidateSet, ValidateRange)
- Script files, comment-based help, and #requires
- Error handling with try/catch/finally and ErrorAction
Writing Functions
Functions in PowerShell follow the same Verb-Noun convention as cmdlets. A basic function uses a param block for parameters:
function Get-Greeting {
param(
[string]$Name = "World"
)
"Hello, $Name!"
}
Get-Greeting -Name "Alice" # Hello, Alice!For production-quality functions, add [CmdletBinding()] to enable common parameters like -Verbose, -ErrorAction, and -WhatIf:
function Remove-OldLogs {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$Path,
[int]$DaysOld = 30
)
$cutoff = (Get-Date).AddDays(-$DaysOld)
Get-ChildItem $Path -Filter "*.log" |
Where-Object LastWriteTime -lt $cutoff |
ForEach-Object {
if ($PSCmdlet.ShouldProcess($_.Name, "Delete")) {
Remove-Item $_.FullName
}
}
}⚠️ Common Mistake
Don't use return for every output. In PowerShell, any unassigned expression is output. return is only needed to exit early. Writing return $result works but is unnecessary at the end of a function.
Functions & Parameters
Build functions with validated parameters.
// PowerShell Functions — simulated in JavaScript
console.log("=== Basic Functions ===");
console.log();
console.log("function Get-Greeting {");
console.log(' param([string]$Name = "World")');
console.log(' return "Hello, $Name!"');
console.log("}");
console.log();
// Simulate
function getGreeting(name = "World") { return "Hello, " + name + "!"; }
console.log("PS> Get-Greeting");
console.log("→ " + getGreeting());
console.log("PS> Get-Greeting -Name 'Alice'");
console.log("→ " + getGreeti
...Scripts, Errors & Modules
Save your functions in .ps1 files and run them with .\script.ps1. Add comment-based help so users can run Get-Help .\script.ps1:
<#
.SYNOPSIS
Backs up a folder to a timestamp directory.
.PARAMETER Source
The folder to back up.
.EXAMPLE
.\Backup-Folder.ps1 -Source C:\Data
#>PowerShell distinguishes between terminating and non-terminating errors. Use -ErrorAction Stop to make non-terminating errors catchable:
try {
Get-Content "missing.txt" -ErrorAction Stop
} catch {
Write-Warning "Error: $($_.Exception.Message)"
}Scripts & Error Handling
Script structure, error handling, and modules.
// PowerShell Scripts & Error Handling — simulated in JavaScript
console.log("=== Script Files (.ps1) ===");
console.log();
console.log("Save functions in .ps1 files and run them:");
console.log(" PS> .\\my-script.ps1");
console.log(" PS> & 'C:\\Scripts\\backup.ps1'");
console.log();
console.log("=== Script Structure Best Practice ===");
console.log("#requires -Version 7.0");
console.log("#requires -Modules ActiveDirectory");
console.log();
console.log("<#");
console.log(".SYNOPSIS");
console
...💡 Pro Tip
Create a PowerShell module by saving your functions in a .psm1 file and creating a module manifest (.psd1) with New-ModuleManifest. This lets you version, share, and publish your tools to the PowerShell Gallery.
📋 Quick Reference
| Concept | Syntax |
|---|---|
| Basic function | function Verb-Noun { param(...) } |
| Mandatory param | [Parameter(Mandatory)] |
| Validate values | [ValidateSet('A','B')] |
| Try/catch | try { ... } catch { ... } |
| Run script | .\script.ps1 |
🎉 Lesson Complete!
You can now write professional PowerShell functions and scripts. Next up: navigating the file system and Windows registry.
Sign up for free to track which lessons you've completed and get learning reminders.