Hi,
I am trying to append the error produced by the erroneous directory path. I am wondering why it is not adding into the error log?
$tested = 'c:\testswtgreg', 'c:\sadfdsafsafsagsa'
try {
Get-ChildItem $tested | foreach-object { Remove-item $_ -Recurse -Force -ErrorVariable myerr -ErrorAction Stop }
} catch {
$myerr | Out-File c:\temp\error.txt -Append
}
i know why,
Ihad trhe error variable stop at the wrong place.
The catch in that block is actually referencing Get-ChildItem $tested
so it really should be Get-ChildItem $tested -ErrorAction Stop -ErrorVariable myerr
Hi Wei,
You only have the -ErrorAction Stop on the Remove-item, but the script is actually erring on Get-ChiltItem, not Remove-item.
Add -ErrorAction Stop to your Get-ChildItem.
Also, you don’t have to specify the ErrorVariable, you can use $_ to get the current error.
$tested = 'c:\testswtgreg', 'c:\sadfdsafsafsagsa'
try {
Get-ChildItem $tested -ErrorAction Stop | foreach-object { Remove-item $_ -Recurse -Force -ErrorAction Stop }
} catch {
$_.CategoryInfo.Activity
$_.Exception.Message
}
Hey Wei,
Good job debugging it while I was replying.
Thanks for the last bit. Thats exactly what i need. Because I need to append detailed information to the log.
I am presuming then in this line:
Remove-item $_ -Recurse -Force -ErrorAction Stop
I can create its own block and add the details in that one too?
Thanks for this. What I have been trying to work on for a while can finally be finished.
That is correct if either one of those those a terminating error, which is what will happen with -ErrorAction Stop, then they get sent to the catch block which will work with the current error whether it was on Get-ChildItem or Remove-Item.