我正在使用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。
答案 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逻辑中的一个异常生成异常信息引起的,但是此包装程序确实可以解决您的问题。