PowerShell:无法捕获get-content引发的UnauthorizedAccessException

时间:2014-07-30 09:47:07

标签: powershell exception-handling

我正在尝试捕获System.UnauthorizedAccessException。如果用户没有对特定文件的读访问权,则会发生此异常。

$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"
}

但我不断收到此错误消息:

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

我在这里做错了什么?


感谢您的回答。我仍然不明白为什么这次运行进入[Exception]而不是更具体的[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"
}

1 个答案:

答案 0 :(得分:6)

try / catch只会捕获终止错误。 您可以在脚本之上使用以下命令使所有错误成为终止错误

$erroractionPreference="stop"

@Shay Levy在这里有解释:https://stackoverflow.com/a/8381798/381149