Functions & Parameters
1. Create a Reusable Function
Define a function with a param block for server health checks.
function Get-ServerHealth { param([string]$ComputerName) Get-Service -ComputerName $ComputerName }
2. Use Parameter Validation
Create a function with ValidateSet to restrict input values.
function Set-Environment { param([ValidateSet('Dev','Test','Prod')]$Env) Write-Output "Setting $Env" }
3. Create an Advanced Function
Build a function with CmdletBinding for -Verbose and -WhatIf support.
function Restart-AppPool { [CmdletBinding(SupportsShouldProcess)] param([string]$Name) }
Pipeline & Filtering
4. Filter with Where-Object
Use Where-Object to filter services by their start type.
Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -eq 'Stopped' }
5. Transform with ForEach-Object
Use ForEach-Object to process each item in a pipeline.
Get-Process | ForEach-Object { "$($_.Name): $([math]::Round($_.WorkingSet64/1MB, 2)) MB" }
6. Select Specific Properties
Use Select-Object to choose and rename output properties.
Get-Process | Select-Object Name, Id, @{N='MemMB';E={[math]::Round($_.WorkingSet64/1MB)}}
Error Handling
7. Try/Catch Error Handling
Wrap a command in try/catch to handle errors gracefully.
try { Get-Service -Name "FakeService" -ErrorAction Stop } catch { Write-Warning $_.Exception.Message }
8. Set Error Action Preference
Configure the global error action to stop on any error.
$ErrorActionPreference = "Stop"
Data Import & Export
9. Export Data to CSV
Export process data to a CSV file for reporting.
Get-Process | Select-Object Name, Id, CPU | Export-Csv -Path "C:\Reports\processes.csv" -NoTypeInformation
10. Import Data from CSV
Read data from a CSV file back into PowerShell objects.
Import-Csv -Path "C:\Reports\processes.csv"
Scheduling & Remote Management
11. Create a Scheduled Task
Register a scheduled task to run a PowerShell script daily at 2 AM.
Register-ScheduledTask -TaskName "DailyBackup" -Trigger (New-ScheduledTaskTrigger -Daily -At 2am) -Action (New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\Backup.ps1")
12. View Scheduled Tasks
List all registered scheduled tasks on the system.
Get-ScheduledTask
13. Remote Command Execution
Run a command on a remote server using Invoke-Command.
Invoke-Command -ComputerName DC02 -ScriptBlock { Get-Service | Where-Object Status -eq 'Running' }
14. Create a Persistent Remote Session
Establish a reusable PSSession for multiple remote commands.
$session = New-PSSession -ComputerName DC02, FS01
Key Automation Cmdlets:
ForEach-Object - Process pipeline itemsWhere-Object - Filter pipeline itemsSelect-Object - Choose propertiesExport-Csv / Import-Csv - Data filesInvoke-Command - Remote executionRegister-ScheduledTask - Automation
Tip: Use
-WhatIf and -Confirm parameters to safely test automation scripts before running them in production. Add [CmdletBinding(SupportsShouldProcess)] to your functions.
Script Signing:
Production environments should use
Production environments should use
Set-ExecutionPolicy AllSigned.
Sign scripts with Set-AuthenticodeSignature and a code signing certificate.
This prevents unauthorized script modifications.
Pipeline Efficiency:
The pipeline streams objects one at a time, keeping memory usage low.
Use
ForEach-Object for pipeline streaming, and foreach
(the statement) when you need all objects loaded into memory first.
Execution Policies:
Restricted - No scripts allowed (default on desktops)
AllSigned - Only signed scripts run
RemoteSigned - Downloaded scripts must be signed
Unrestricted - All scripts run (warns on downloaded)
Bypass - Nothing is blocked, no warnings
Restricted - No scripts allowed (default on desktops)
AllSigned - Only signed scripts run
RemoteSigned - Downloaded scripts must be signed
Unrestricted - All scripts run (warns on downloaded)
Bypass - Nothing is blocked, no warnings
Creating a Module:
1. Create a folder matching the module name
2. Place your .psm1 file inside with exported functions
3. Create a .psd1 manifest with
4. Place in
5. Use
1. Create a folder matching the module name
2. Place your .psm1 file inside with exported functions
3. Create a .psd1 manifest with
New-ModuleManifest4. Place in
$env:PSModulePath for auto-discovery5. Use
Import-Module to load manually
Remoting Security:
PowerShell Remoting uses WinRM (WS-Management) over port 5985 (HTTP)
or 5986 (HTTPS). Always use HTTPS in production.
Enable remoting with
Enable-PSRemoting -Force.
Use TrustedHosts for workgroup environments.
Common Parameter Validation Attributes:
[ValidateSet()] - Restrict to specific values[ValidateRange()] - Numeric range limits[ValidateLength()] - String length limits[ValidatePattern()] - Regex pattern match[ValidateNotNullOrEmpty()] - Require a value[ValidateScript()] - Custom validation logic