Mat*_*tze 3 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"
}
Run Code Online (Sandbox Code Playgroud)
但我不断收到此错误消息:
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
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
谢谢回答.我仍然不明白为什么这个运行进入[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"
}
Run Code Online (Sandbox Code Playgroud)