system.security.principal.IdentityNotMappedException捕获所有错误



我在尝试/捕获块中遇到问题,其中System.Security.Principal.IdentityNotMappedException的捕获块正在捕获所有错误,无论它们是否属于System.Security.Principal.IdentityNotMappedException型。问题是,当我将尝试/捕获块移出脚本外部进行测试时,尝试/捕获按预期工作。

尝试/捕获在/每个内部/每个都可以想到的是,循环在某种程度上绊倒了尝试/捕获块?它喜欢捕获的一个错误是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    
    }
}

这不是我问题的答案(因为我不完全理解它发生的原因,因此可能会遇到其他问题(,而是将-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很奇怪。

最新更新