PowerShell Automation Examples
This lesson puts the course together in small, realistic automation scripts, the kind you'd schedule to run every night or keep in a team's toolbox. Each example builds its own sample files first so it can run anywhere; in real use you'd point it at your actual folders.
1. Log rotation with retention
Keep the newest N log files, compress older ones into an archive and delete them:
# --- sample data: 6 log files with fixed dates ---
New-Item -ItemType Directory ./app/logs -Force | Out-Null
1..6 | ForEach-Object {
$f = New-Item -ItemType File "./app/logs/app-2026-03-0$_.log" -Value "log $_" -Force
$f.LastWriteTime = [datetime]"2026-03-0$_"
}
# --- the actual job ---
$keep = 3
$logs = Get-ChildItem ./app/logs -Filter *.log | Sort-Object LastWriteTime -Descending
$old = $logs | Select-Object -Skip $keep
Compress-Archive -Path $old.FullName -DestinationPath ./app/logs/archive.zip -Force
$old | Remove-Item
"Kept: $((Get-ChildItem ./app/logs -Filter *.log -Name) -join ', ')"
Expand-Archive ./app/logs/archive.zip -DestinationPath ./restored -Force
"Archived: $((Get-ChildItem ./restored -Name) -join ', ')"Kept: app-2026-03-04.log, app-2026-03-05.log, app-2026-03-06.log
Archived: app-2026-03-01.log, app-2026-03-02.log, app-2026-03-03.log
2. A health report from data files
Read a CSV of servers and a JSON of measurements, join them, and flag problems:
@'
Name,Role,MaxCpu
web01,frontend,80
web02,frontend,80
db01,database,90
'@ | Set-Content ./servers.csv
@'
[
{ "server": "web01", "cpu": 45, "diskFreePct": 40 },
{ "server": "web02", "cpu": 88, "diskFreePct": 35 },
{ "server": "db01", "cpu": 72, "diskFreePct": 8 }
]
'@ | Set-Content ./metrics.json
$servers = Import-Csv ./servers.csv
$metrics = Get-Content ./metrics.json -Raw | ConvertFrom-Json
$byName = $metrics | Group-Object server -AsHashTable
$report = foreach ($s in $servers) {
$m = $byName[$s.Name][0]
$problems = @()
if ($m.cpu -gt [int]$s.MaxCpu) { $problems += "CPU $($m.cpu)%" }
if ($m.diskFreePct -lt 10) { $problems += "disk $($m.diskFreePct)% free" }
[pscustomobject]@{
Server = $s.Name
Role = $s.Role
Status = $problems.Count ? 'ALERT' : 'OK'
Detail = $problems -join ', '
}
}
$report | Format-Table -AutoSize
"{0} of {1} servers need attention" -f @($report | Where-Object Status -eq 'ALERT').Count, $report.Count
Server Role Status Detail
------ ---- ------ ------
web01 frontend OK
web02 frontend ALERT CPU 88%
db01 database ALERT disk 8% free
2 of 3 servers need attention
3. Bulk renaming files
Rename camera-style files to a sortable, descriptive scheme. Run with -WhatIf first, then for real:
New-Item -ItemType Directory ./photos -Force | Out-Null
'IMG_0042.JPG', 'IMG_0007.JPG', 'IMG_0113.jpg' | ForEach-Object { Set-Content "./photos/$_" 'x' }
$files = Get-ChildItem ./photos -Filter 'IMG_*' | Sort-Object Name
$i = 0
foreach ($file in $files) {
$i++
$newName = 'holiday-{0:D3}{1}' -f $i, $file.Extension.ToLower()
Rename-Item $file.FullName -NewName $newName -WhatIf
}
'---'
$i = 0
foreach ($file in $files) {
$i++
Rename-Item $file.FullName -NewName ('holiday-{0:D3}{1}' -f $i, $file.Extension.ToLower())
}
Get-ChildItem ./photos -NameWhat if: Performing the operation "Rename File" on target "Item: /tmp/photos/IMG_0007.JPG Destination: /tmp/photos/holiday-001.jpg".
What if: Performing the operation "Rename File" on target "Item: /tmp/photos/IMG_0042.JPG Destination: /tmp/photos/holiday-002.jpg".
What if: Performing the operation "Rename File" on target "Item: /tmp/photos/IMG_0113.jpg Destination: /tmp/photos/holiday-003.jpg".
---
holiday-001.jpg
holiday-002.jpg
holiday-003.jpg
4. Generating config files from a template
Create one config file per environment from a single template and a data table:
$template = @'
# generated - do not edit
environment = {0}
api_url = https://{1}/api
replicas = {2}
debug = {3}
'@
$environments = @(
[pscustomobject]@{ Name = 'dev'; Host = 'dev.example.com'; Replicas = 1; Debug = $true }
[pscustomobject]@{ Name = 'prod'; Host = 'example.com'; Replicas = 4; Debug = $false }
)
New-Item -ItemType Directory ./config -Force | Out-Null
foreach ($e in $environments) {
$content = $template -f $e.Name, $e.Host, $e.Replicas, $e.Debug.ToString().ToLower()
Set-Content -Path "./config/$($e.Name).conf" -Value $content
}
Get-ChildItem ./config -Name
Get-Content ./config/prod.confdev.conf
prod.conf
# generated - do not edit
environment = prod
api_url = https://example.com/api
replicas = 4
debug = false
5. A reusable tool with parameters and logging
Package a job as an advanced function with validation, -WhatIf support and a log, ready to be put in a module:
function Clear-TempFiles {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)][ValidateScript({ Test-Path $_ -PathType Container })]
[string]$Path,
[string[]]$Extension = @('.tmp', '.bak'),
[string]$LogFile = './cleanup.log'
)
$targets = Get-ChildItem $Path -File -Recurse | Where-Object Extension -in $Extension
$removed = 0
foreach ($t in $targets) {
if ($PSCmdlet.ShouldProcess($t.Name, 'Remove')) {
Remove-Item $t.FullName
Add-Content $LogFile "removed $($t.Name)"
$removed++
}
}
[pscustomobject]@{ Path = $Path; Found = @($targets).Count; Removed = $removed }
}
New-Item -ItemType Directory ./build/cache -Force | Out-Null
'a.tmp', 'b.bak', 'keep.txt', 'cache/c.tmp' | ForEach-Object { Set-Content "./build/$_" 'x' }
Clear-TempFiles -Path ./build -WhatIf
Clear-TempFiles -Path ./build
Get-Content ./cleanup.log
try { Clear-TempFiles -Path ./nope } catch { 'Invalid path rejected by ValidateScript' }What if: Performing the operation "Remove" on target "a.tmp".
What if: Performing the operation "Remove" on target "b.bak".
What if: Performing the operation "Remove" on target "c.tmp".
Path Found Removed
---- ----- -------
./build 3 0
./build 3 3
removed a.tmp
removed b.bak
removed c.tmp
Invalid path rejected by ValidateScript
Scheduling your scripts
| Platform | Scheduler | Command it runs |
|---|---|---|
| Windows | Task Scheduler (Register-ScheduledTask) |
pwsh.exe -NoProfile -File C:\Scripts\job.ps1 |
| Linux | cron / systemd timer | pwsh -NoProfile -File /opt/scripts/job.ps1 |
| CI/CD | GitHub Actions, Azure Pipelines (shell: pwsh) |
the script file from the repository |
Tip: For scheduled scripts: use
-NoProfile, set$ErrorActionPreference = 'Stop', log what you did, andexitwith a non-zero code on failure so the scheduler can alert you.
Test yourself
In the log rotation example, what does Select-Object -Skip $keep select?
- The newest files
- All files except the first $keep of the sorted list, i.e. the older ones
- Every second file
- Files larger than $keep
Why run a bulk rename with -WhatIf first?
- It is faster
- To preview exactly which files would be renamed before changing anything
- WhatIf is required by Rename-Item
- It creates a backup
Which command line is suitable for running a script from a scheduler?
- pwsh
- pwsh -NoProfile -File ./job.ps1
- powershell_ise job.ps1
- ./job.ps1 &