ForEach循环两次而不是一次迭代-Powershell

时间:2020-02-19 15:19:40

标签: powershell foreach

我再次打破了foreach循环,无法弄清原因。它似乎对一些帐户进行了两次迭代,而不是一次。我认为我的{}格式正确,但显然没有。谁能帮助我找到我所缺少的东西?

相关代码:

foreach ($OU in $OUs) {

    # Search for User and/or Computer Objects inactive for XX days.  Disable object if not in DoNotDisable Security Groups
    $days = $days + "D"
    $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -AccountInactive -TimeSpan ([timespan]7D) @scope
    foreach($account in $accounts){
        If ($noDisable -notcontains $account.Name) {
            Write-Host $account
    #        #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
       }
    }
}

输出:每个计算机帐户列出两次两次,除了后2个。

enter image description here

1 个答案:

答案 0 :(得分:3)

如果您的目录树如下所示:

NC root
 |- TopLevelOU
     |- SubOU
     |   |- Computer1
     |   |- Computer2
     |- Computer3
     |- Computer4

...,然后从查询所有OU开始,然后(递归)搜索每个对象,您将在SubOU 两次下获得每个对象-一次是通过TopLevelOU搜索,另一次是直接针对SubOU搜索。

如果要将每个搜索包含到目标OU的直接子级中,请在您的-SearchScope OneLevel调用中添加Search-ADAccount

$accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -SearchScope OneLevel -AccountInactive -TimeSpan ([timespan]7D) @scope