-WhatIf is a PowerShell switch for previewing an operation without performing it. It is especially useful before irreversible work such as deleting archived log files. section 2.1.6
A switch acts like a Boolean parameter: including -WhatIf sets it to true. A reusable function can accept the switch and pass its value to a destructive cmdlet with -WhatIf:$WhatIf. section 2.1.6
Listing 2.2 Deleting archived files
Function Remove-ArchivedFiles {
[CmdletBinding()]
[OutputType()]
param(
[Parameter(Mandatory = $true)]
[string]$ZipFile,
[Parameter(Mandatory = $true)]
[object]$FilesToDelete,
[Parameter(Mandatory = $false)]
[switch]$WhatIf = $false
)
$AssemblyName = 'System.IO.Compression.FileSystem' #1
Add-Type -AssemblyName $AssemblyName | Out-Null
$OpenZip = [System.IO.Compression.ZipFile]::OpenRead($ZipFile)
$ZipFileEntries = $OpenZip.Entries #2
foreach($file in $FilesToDelete){ #3
$check = $ZipFileEntries | Where-Object{ $_.Name -eq $file.Name -and
$_.Length -eq $file.Length }
if($null -ne $check){ #4
$file | Remove-Item -Force -WhatIf:$WhatIf #5
}
else {
Write-Error "'$($file.Name)' was not find in '$($ZipFile)'"
}
}
}
The removal function verifies that each candidate file exists in the ZIP archive, then forwards its WhatIf value to Remove-Item rather than deleting blindly. section 2.1.6
Preview archive cleanup
After compressing selected log files, run Remove-ArchivedFiles with -WhatIf. PowerShell reports each “Remove File” operation while the original files remain in place; rerun without the switch only after checking the preview. section 2.1.7
Use -WhatIf as part of a cautious automation workflow:
- Collect and inspect the files selected for archiving. section 2.1.7
- Create the archive before testing deletion. section 2.1.7
- Review the reported targets, then run without -WhatIf when they are correct. section 2.1.7
- Run a final script test in a new PowerShell window to avoid values or functions left in memory. section 2.1.7
