为什么我 运行 作为域管理员执行此功能时没有抛出错误?

Why aren't error thrown when I run this function as domain administrator?

此脚本旨在通过一系列目录进行递归,当抛出类型为 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 我该怎么做才能确保收到错误以及我的 Take-Ownership 函数其实叫什么?

如果 $errz.Count 为 0,您的代码仅进入 if 块。计数为 0 时,$errz 中没有元素,因此 [=] 无需执行任何操作13=]循环。

在条件语句中添加一个 else 分支,将 foreach 循环移动到那里,代码应该会执行您想要的操作。

if ($errz.Count -eq 0) {
    Write-Host "blah no errors"
<b>} else {</b>
    foreach ($err in $errz) { 
        Write-Host "Error: $err"
        ...
    }
}