使用Get-Acl时获取引起UnauthorizedAccessException的文件或目录的路径

时间:2018-10-22 06:49:24

标签: powershell powershell-v2.0

我正在使用Powershell命令import_orders_products_op.pre_execute(context=kwargs)

如果此命令由于运行用户的用户对某些文件或目录的权限不足而失败,则会引发以下错误:

import_orders_products_op.execute(context=kwargs)

处理此异常时,我想打印出导致权限错误的文件或目录的路径。

如何获取导致此错误的文件或目录的路径?

我尝试使用诸如$TargetFiles = Get-Childitem $TargetPath -Recurse -ErrorAction Stop | Get-Acl之类的命令,并研究了诸如Get-Acl : Attempted to perform an unauthorized operation. At B:\PS\Script.ps1:20 char:50 + $TargetFiles = Get-Childitem $TargetPath -Recurse -ErrorAction Stop <<<< + CategoryInfo : NotSpecified: (:) [Get-Acl], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetAclCommand 之类的变量,但是从它们中找不到此信息。

我正在使用的Powershell版本:

Get-PSCallStack

操作系统是Windows 7。

2 个答案:

答案 0 :(得分:2)

您可以使用$Error自动变量来查看遇到异常的过程。像这样:

$TargetFiles = Get-Childitem $TargetPath -Recurse -ErrorAction Stop

$Error[0]
$Error[0].ErrorRecord.CategoryInfo
$Error[0].ErrorRecord.CategoryInfo.TargetName

答案 1 :(得分:1)

不幸的是,似乎Get-Acl是引发异常的代码,尽管它与Get-ChildItem返回的异常类型相同,但消息却不同(Attempted to perform an unauthorized operation Access to the path 'c:\whatever' is denied),并且它的数据中不包含违规路径。

解决方法是这样:

try {
    $TargetFiles = $TargetPath | Get-Childitem -Recurse -ErrorAction Stop | ForEach-Object{$_ | Get-Acl -ErrorAction Stop}
} catch [System.UnauthorizedAccessException] {
    $pathWithProblem = $_.TargetObject
    #do what you like with it after this
    $descriptionOfProblem = $_.Exception.Message
    Write-Warning "$descriptionOfProblem : $pathWithProblem"
    throw
}

这看起来有点傻;因为我们只是将对Get-ACL的调用包装在foreach块中;无论如何,其逻辑由管道输入来处理。我敢肯定,这种异常行为是由PS逻辑中的一个异常生成异常信息引起的,但是此包装程序确实可以解决您的问题。