此脚本旨在通过一系列目录进行递归,当出现DirUnauthorizedAccessError,Microsoft
或PowerShell.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}函数实际上是被调用的吗?
答案 0 :(得分:1)
如果if
为0,您的代码只会输入$errz.Count
块。如果计数为0,$errz
中没有元素,那么{{1}无关}循环。
在条件中添加foreach
分支,在那里移动else
循环,代码应该按照您的意愿执行。
foreach