Reputation: 493
I'm trying to get some information of an Remove-Item
operation in PowerShell.
Since I don't want the loop to stop when one Item on Remove-Item
failes, I can't use Try{} catch{}
and -ErrorAction Stop
Is there a way to get error information i want without clearing the error variable before Remove-Item
, and also without having to use a loop to iterate over the files?
$error.clear()
$Files | Remove-Item -Force
0..($error.count - 1) | % {
$x = $Error[$_].CategoryInfo
$y = "{0}, {1}, {2}" -f $x.Category, $x.Reason, $x.TargetName
$ResultLog += [PSCustomObject]@{Result="Error"; Path=$p.path; Message=$y}
}
Upvotes: 0
Views: 32
Reputation: 484
I like @HAL9256's gusto but I think using $Error.count is a bad idea. The count only goes up to 256 items before it stops counting up and starts dropping off the oldest errors. Depending on the volume of files and errors, you could easily run out of room there.
https://devblogs.microsoft.com/scripting/powershell-error-handling-and-why-you-should-care/
Rather than using the pipeline, I think a foreach would be better suited.
$ResultLog = @()
foreach ($file in $files) {
try {
Remove-Item $file -Force -ErrorAction Stop
} catch {
$x = $_.CategoryInfo
$y = "{0}, {1}, {2}" -f $x.Category, $x.Reason, $x.TargetName
$ResultLog += [PSCustomObject]@{Result="Error"; Path=$p.path; Message=$y}
}
}
Upvotes: 1
Reputation: 13523
Use -ErrorAction Continue
It won't halt the running of the script but will still add to the $Error
variable.
To not have to clear the $Error
variable before running, since the $Error
variable is an array, simply store the Error count before running, and then use a For
loop to only iterate through the new messages.
$ErrorsBefore = $Error.Count
$Files | Remove-Item -Force -ErrorAction Continue
$ResultLog = @()
For($i=0 ; $i -lt ($error.count - $ErrorsBefore); $i++) {
$x = $Error[$i].CategoryInfo
$y = "{0}, {1}, {2}" -f $x.Category, $x.Reason, $x.TargetName
$ResultLog += [PSCustomObject]@{Result="Error"; Path=$p.path; Message=$y}
}
Upvotes: 0