Trap remove-item exception
-
30-04-2021 - |
Question
In powershell there is some exception that I am not able to trap or I am not doing to correct things.
So here is the code that does the things:
log "Processing $($_.Name).old" $logFile
if (Test-Path "$($_.Name).old" )
{
& {
rm "$($_.Name).old"
}
trap #[System.UnauthorizedAccessException]
{
log "Move to trash" $logFile
moveTrach "$($_.Name).old"
continue
}
}
I had comment out the type in the trap expression to be sure to catch anything. But unfortunately I never go into the trap clause.
I can see the exception log but not the "Move to trash" log.
2012-02-16 10:35:31 Processing file.dll
Remove-Item : Cannot remove item file.dll.old: Access to the path 'file.dll.old' is denied.
At upgradegw.ps1:189 char:29
+ rm <<<< "$($_.Name).old"
+ CategoryInfo : PermissionDenied: (file.dll.old:FileInfo) [Remove-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
2012-02-16 10:35:31 Processing file2.dll
Solution
The trap will only trigger on a terminating error.
rm "$($_.Name).old" -ErrorAction "Stop"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow