I want to run a loop, and continue through terminating errors, but save the error info for later.
Something like this I tried with ErrorVariable:
Sample code 1
foreach ($index in 0..10) {
Write-Host $index
if ($index -eq 6 -or $index -eq 8) {
Get-ChildItem -Path C:\DoesNotExist\ -ErrorAction SilentlyContinue -ErrorVariable +test
}
}
$test
Sample code output
0
1
2
3
4
5
6
7
8
9
10
Get-ChildItem : Cannot find path 'C:\DoesNotExist\' because it does not exist.
At line:5 char:9
+ Get-ChildItem -Path C:\DoesNotExist\ -ErrorAction SilentlyCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\DoesNotExist\:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Get-ChildItem : Cannot find path 'C:\DoesNotExist\' because it does not exist.
At line:6 char:9
+ Get-ChildItem -Path C:\DoesNotExist\ -ErrorAction SilentlyCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\DoesNotExist\:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
The problem with the output is that it doesn't contain further details on the error instance, how can I know which loop index that the error occurred?
An alternative thought I had was using trap, but trap won't work with the loop
Sample code 2
foreach ($index in 0..10) {
Write-Host $index
if ($index -eq 6 -or $index -eq 8) {
Get-ChildItem -Path C:\DoesNotExist\ -ErrorAction SilentlyContinue
}
}
trap {
Write-Host "Trap $index" -ForegroundColor Cyan
Write-Error $error[0]
continue
}
Psuedo desired output
0
1
2
3
4
5
6
Trap 6
: Cannot find path 'C:\DoesNotExist\' because it does not exist.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Trap 8
: Cannot find path 'C:\DoesNotExist\' because it does not exist.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Two alternatives, using a try / catch instead of trap, this method requires -ErrorAction Stop:
foreach ($index in 0..10) {
Write-Host $index
if ($index -eq 6 -or $index -eq 8) {
try {
Get-ChildItem -Path C:\DoesNotExist\ -ErrorAction Stop
}
catch {
Write-Host "Catch $index" -ForegroundColor Cyan
Write-Error $_
}
}
}
Using -ErrorVariable but instead of adding to the array list just overwrite it and check if there were errors, if so, write them:
foreach ($index in 0..10) {
Write-Host $index
if ($index -eq 6 -or $index -eq 8) {
Get-ChildItem -Path C:\DoesNotExist\ -ErrorAction SilentlyContinue -ErrorVariable test
if ($test) {
Write-Host "Catch $index" -ForegroundColor Cyan
$test | Write-Error
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With