Write-Error sends an error to PowerShell without terminating execution. Use it when a recoverable problem should be recorded while a loop or automation task continues. section 2.1.6
Choose Write-Error when processing can continue after the failure:
- Compare expected archive files with actual entries, delete matching files, and record missing files without stopping the remaining checks. section 2.1.6
- Report an external process failure after monitoring its runtime; use throw instead when the failure must terminate the script. section 9.4.2
Archive cleanup
Remove-ArchivedFiles opens a ZIP archive, checks each requested file by name and size, removes matches, and uses Write-Error for files that are absent. Its WhatIf switch supports safer execution. 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)'"
}
}
}
Inspect the complete Remove-ArchivedFiles function, including parameters, ZIP access, file matching, deletion, and WhatIf handling. section 2.1.6
