System.Security.Principal.IdentityNotMappedException捕获所有错误

时间:2018-02-14 21:03:20

标签: powershell

我遇到了try / catch块的问题,其中System.Security.Principal.IdentityNotMappedException的catch块正在捕获所有错误,无论它们是否为System.Security.Principal.IdentityNotMappedException类型。问题是当我将脚本外部的try / catch块移动到它自己的测试中时,try / catch按预期工作。

try / catch在for / each中,所以我只能想到循环是以某种方式绊倒try / catch块?它喜欢捕捉的一个错误是System.Management.Automation.RuntimeException

下面是我制作的测试脚本按预期工作,但放在foreach中的不是:

我确实错误地表明了这一点:

foreach($x in Get-ChildItem){
    Get-Acl "C:\fake"
    try {
        $Acl = Get-Acl
        Set-Acl LiteralPath "C:\temp" $Acl -ErrorAction Stop
        Write-Host "Access Rule Added" -ForegroundColor Cyan            
    }            
    catch [System.UnauthorizedAccessException] {                
        Write-Host "Insufficient Priviliege. Owner: $($Acl.Owner) ($_)" -ForegroundColor Red    

    }
    catch [System.Security.Principal.IdentityNotMappedException] {
        Write-Host "Invalid Prinicpal! ($_)" -ForegroundColor Red
        $abort = Read-Host -Prompt "Abort? (Y)"
        if($abort -ieq "Y"){ Exit }
    }
    catch {
        Write-Host "ALL: $_" -ForegroundColor Red    
    }
}

1 个答案:

答案 0 :(得分:0)

这不是我的问题的答案(因为我不完全理解为什么会发生这种情况,因此可能会对其他问题产生影响),但是将-ErrorAction SilentlyContinue添加到Get-Acl抛出第一个错误的命令有助于防止错误捕获:

foreach($x in Get-ChildItem){
    Get-Acl "C:\fake" -ErrorAction SilentlyContinue
    try {
        $Acl = Get-Acl
        Set-Acl LiteralPath "C:\temp" $Acl -ErrorAction Stop
        Write-Host "Access Rule Added" -ForegroundColor Cyan            
    }            
    catch [System.UnauthorizedAccessException] {                
        Write-Host "Insufficient Priviliege. Owner: $($Acl.Owner) ($_)" -ForegroundColor Red    

    }
    catch [System.Security.Principal.IdentityNotMappedException] {
        Write-Host "Invalid Prinicpal! ($_)" -ForegroundColor Red
        $abort = Read-Host -Prompt "Abort? (Y)"
        if($abort -ieq "Y"){ Exit }
    }
    catch {
        Write-Host "ALL: $_" -ForegroundColor Red    
    }
}

虽然很奇怪$_如何显示实际错误,但在这种情况下只显示AclObject