UnauthorizedAccessException

UnauthorizedAccessException

我正在 try catch 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"
}

最佳答案

try/catch 将只捕获终止错误。
您可以在脚本之上使用以下命令使所有错误成为终止错误
$erroractionPreference="stop"
@Shay Levy 有解释:https://stackoverflow.com/a/8381798/381149

关于PowerShell:无法捕获 get-content 抛出的 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25033668/

10-12 04:52