当我以域管理员身份运行此功能时,为什么不会抛出错误?

时间:2016-08-25 15:00:50

标签: powershell file-permissions

此脚本旨在通过一系列目录进行递归,当出现DirUnauthorizedAccessError,MicrosoftPowerShell.Commands.GetChildItemCommand类型的错误时,它应该调用另一个函数Take-Ownership目录的所有权,并将localAdmin和域管理员的完全权限添加到该文件夹​​。 (它实际上是用于简化旧用户配置文件删除的脚本):

function Test-Folder($FolderToTest, $localAdminName) {
    # Remeber the old error preference...
    $old_ErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = 'SilentlyContinue'

    $error.Clear()

    # Go through the directories...and capture errors in $error 
    Get-ChildItem $FolderToTest -Recurse -ErrorAction SilentlyContinue -ErrorVariable errz | Select FullName

    Write-Host $errz.count

    if ($errz.Count -eq 0) {
        Write-Host "blah no errors"
        foreach ($err in $errz) { 
            Write-Host "Error: $err"
            if ($err.FullyQualifiedErrorId -eq "DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand") {
                Write-Host Unable to access $err.TargetObject -Fore Red
                Write-Host Attempting to take ownership of $err.TargetObject -Fore Yellow
                Take-Ownership -Folder $err.TargetObject, -LocalAdminName $localAdminName
                Test-Folder -FolderToTest $err.TargetObject -localAdminName $localAdminName
            }
        }
    }

    $ErrorActionPreference = $old_ErrorActionPreference 
}

不幸的是,当我以域管理员身份运行它时,它不会抛出任何错误。我找到了ErrorActionPreferences here的列表,但错误似乎被忽略了,它输出blah no errors我该怎么做才能确保收到错误并且我的{{1}函数实际上是被调用的吗?

1 个答案:

答案 0 :(得分:1)

如果if为0,您的代码只会输入$errz.Count块。如果计数为0,$errz中没有元素,那么{{1}无关}循环。

在条件中添加foreach分支,在那里移动else循环,代码应该按照您的意愿执行。

foreach