Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Can't catch UnauthorizedAccessException thrown by get-content

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"
}
like image 267
Matthias Güntert Avatar asked Jan 11 '23 03:01

Matthias Güntert


1 Answers

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

like image 145
Loïc MICHEL Avatar answered May 11 '23 16:05

Loïc MICHEL