Key Facts
- Functions enable code reuse and reduce repetition in PowerShell scripts
- Modules package functions into distributable units (ps1, psd1, dll files)
- The PSGallery repository hosts 7,000+ PowerShell modules available for download
- Proper parameter validation prevents invalid input from breaking automation
What Are Functions?
Functions are reusable blocks of code that perform a specific task. Instead of writing the same code repeatedly, define a function once and call it many times.
function Get-SystemInfo {
param([string]$ComputerName = $env:COMPUTERNAME)
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $ComputerName
$cpu = Get-CimInstance -ClassName Win32_Processor -ComputerName $ComputerName
[PSCustomObject]@{
ComputerName = $ComputerName
OS = $os.Caption
Memory = [math]::Round($os.TotalVisibleMemorySize / 1MB, 2)
CPUCores = $cpu.NumberOfCores
}
}
# Call the function
Get-SystemInfo
Get-SystemInfo -ComputerName "Server01"
Function Parameters and Validation
Parameters allow functions to accept input. Validation ensures the input meets requirements:
function New-User {
param(
[Parameter(Mandatory=$true)]
[ValidateLength(3,20)]
[string]$Username,
[Parameter(Mandatory=$true)]
[ValidatePattern('^[a-zA-Z]')]
[string]$FirstName,
[Parameter(Mandatory=$true)]
[ValidateSet("IT", "HR", "Finance", "Operations")]
[string]$Department
)
# Function body
Write-Host "Creating user: $Username in $Department"
}
# Valid call
New-User -Username "jdoe" -FirstName "John" -Department "IT"
# Invalid call (too short)
New-User -Username "jd" -FirstName "John" -Department "IT" # Error!