I am trying to catch the System.UnauthorizedAccessException. This exception occurs if a user has no read-access to a specific file.
$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:
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].
$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"
}
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
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