Process collections of files with loops, per-item conditions, and controlled errors.
Sheet: 20 of 25 | Platform: Windows 10/11 | Shell: PowerShell 7.x and Windows PowerShell 5.1 (unless marked otherwise) | Editorial review: November 24, 2026
Examples use the MGU project root and illustrative staging, backup, and download paths. Replace them with existing, approved paths as needed. Unless explicitly marked as a continuation, examples are independent. Read commands before running them; commands that write or modify files can change existing data.
Quick commands
1. Process objects through a pipeline
Get-ChildItem -LiteralPath 'C:\MGU' -File |
ForEach-Object { $_.FullName }
2. Use a foreach statement with a reusable collection
$files = @(Get-ChildItem -LiteralPath 'C:\MGU-Staging' -File)
foreach ($file in $files) {
[pscustomobject]@{Path=$file.FullName; Bytes=$file.Length}
}
3. Skip files outside a condition
foreach ($file in (Get-ChildItem -LiteralPath 'C:\MGU-Staging' -File)) {
if ($file.Extension -ne '.html') { continue }
$file.FullName
}
4. Process files with individual error handling
Get-ChildItem -LiteralPath 'C:\MGU-Staging' -File | ForEach-Object {
try { Get-FileHash -LiteralPath $_.FullName -ErrorAction Stop }
catch { Write-Warning $_.Exception.Message }
}
5. Preview bulk operation with explicit per-item targets
Get-ChildItem -LiteralPath 'C:\MGU-Staging' -File -Filter '*.tmp' |
ForEach-Object { Remove-Item -LiteralPath $_.FullName -WhatIf }
6. Count progress through a fixed collection
$files = @(Get-ChildItem -LiteralPath 'C:\MGU-Staging' -File)
$i = 0
foreach ($file in $files) {
$i++
Write-Progress -Activity 'Inspecting files' -Status $file.Name -PercentComplete (100 * $i / $files.Count)
$file.FullName
}
Write-Progress -Activity 'Inspecting files' -Completed
Operational notes
ForEach-Object streams objects; foreach commonly works with a collection expression. Use -ErrorAction Stop for cmdlets whose failures must enter catch. Do not start parallel mutations until order, collisions, and recovery are understood.