在满足条件后继续执行/ until循环

时间:2017-03-10 14:46:56

标签: powershell active-directory

我在尝试自动将计算机对象从一个OU移动到另一个OU时遇到问题。我试图移动一个OU然后重复多个OU的模式。但是在满足until的条件后,do循环继续。

$groupA = Get-ADObject -LDAPFilter "(&(objectcategory=computer))" -SearchBase "OU=Group,OU=clients,OU=WSUS computers, DC=Domain,DC=com"
$GroupACount = $groupA.Count
$groupA_computers = $groupA | select name -ExpandProperty name
$groupB = "OU=GroupB,OU=clients,OU=WSUS computers, DC=domain,DC=com"

write "group A had $GroupACount Computers"

if ($GroupACount -gt 120) {
    write "Computers need to be moved from group A "
    Start-Sleep 5
    do {
        foreach ($computer in $groupA) {
            Get-ADComputer $computer |
                Move-ADObject -TargetPath $view |
                write "Computer $computer has moved to $groupB"
        }
    } until ($GroupACount -eq "2")
} else {
    write "$groupA is below threshold"
}

1 个答案:

答案 0 :(得分:0)

我会在foreach ($computer in $groupA)循环中添加以下行,以便减少$GroupACount整数,因为目前您的$GroupACount值永远不会更改,因此它永远不会满足Until条件:

$GroupACount--

像这样:

$groupA = Get-ADObject -LDAPFilter "(&(objectcategory=computer))" -SearchBase "OU=Group,OU=clients,OU=WSUS computers, DC=Domain,DC=com"
$GroupACount = $groupA.Count
$groupA_computers = $groupA | select name -ExpandProperty name
$groupB = "OU=GroupB,OU=clients,OU=WSUS computers, DC=domain,DC=com"

write "group A had $GroupACount Computers"

if ($GroupACount -gt 120) {
    write "Computers need to be moved from group A "
    Start-Sleep 5
    do {
        foreach ($computer in $groupA) {
            Get-ADComputer $computer |
                Move-ADObject -TargetPath $view |
                write "Computer $computer has moved to $groupB"
                $GroupACount--
        }
    } until ($GroupACount -eq "2")
} else {
    write "$groupA is below threshold"
}