Question:
I am trying to catch the System.UnauthorizedAccessException. This exception occurs if a user has no read-access to a specific file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$fwlog = $env:SystemRoot + "\system32\logfiles\firewall\pfirewall.log" if(Test-Path $fwlog) { try { Get-Content -ReadCount 10 -Path $fwlog } catch [System.UnauthorizedAccessException] { Write-Host "caught" } } else { write-host "File does not exist" } |
But I keep getting this error message:
1 2 3 4 5 6 7 |
Get-Content : Access to the path 'C:\Windows\system32\logfiles\firewall\pfirewall.log' is denied. At D:\SourceCode\PowerShell\FwLogParser.ps1:7 char:9 + Get-Content -ReadCount 10 -Path $fwlog + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (C:\Windows\syst...l\pfirewall.log:String) [Get-Content], UnauthorizedAccessException + FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand |
What am I doing wrong here?
Thanks for answering. I still don’t understand why this run’s into [Exception] and not into the more specific [System.UnauthorizedAccessException].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$fwlog = $env:SystemRoot + "\system32\logfiles\firewall\pfirewall.log" $ErrorActionPreference = "stop" if(Test-Path $fwlog) { try { Get-Content -ReadCount 10 -Path $fwlog } catch [System.UnauthorizedAccessException] { Write-Host "caught" } catch [Exception] { Write-Host "Caugth generic exception" } } else { write-host "File does not exist" } |
Answer:
try/catch will catch only terminating errors.
You can use the following command on top of your script to make all errors a terminating error
$erroractionPreference="stop"
@Shay Levy has the explaination here : https://stackoverflow.com/a/8381798/381149