x次使用多个ForEach-Object进行递归循环

时间:2017-12-20 12:35:38

标签: powershell recursion active-directory

我一直在使用Recursive DirectReport代码,目的是修改它只能查看X级别的直接下降报告(例如CEO加2级)。

我正在使用额外的$count变量并决定使用if ($count -ge 0) {<code>}$count--来控制递归,但是我已经在代码中上下移动,进出每个For循环,试图找到正确的地方;混合的,有时是搞笑的结果。

当我盯着时,我非常确定将if语句放在Get-ADdirectReports -SamAccountName $_周围将是一个2分钟的工作。我要大约6个多小时才能让它发挥作用。有谁接受挑战?

function Get-ADdirectReports {
    Param($SamAccountName, $count)

    Get-Aduser -Identity $SamAccountName -Properties directreports -Server contoso.net:3268 | ForEach-Object {     
        ($_.directreports) | ForEach-Object {
            # Output the current Object information
            Get-ADUser -Identity $_ -Properties manager -Server contoso.net:3268 |
                Select-Object -Property Name, SamAccountName, @{L="Manager";E={
                    (Get-Aduser -Identity $_.Manager -Server contoso.net:3268).SamAccountName
                }}
            # Find the DirectReports of the current item
            Get-ADdirectReports -SamAccountName $_
        }
    }
}

Get-ADdirectReports TheCEO 5

2 个答案:

答案 0 :(得分:0)

以下代码给出了所需的结果:

function Get-ADdirectReports
{
PARAM ($SamAccountName, $count)

    Get-Aduser -identity $SamAccountName -Properties directreports -server contoso.net:3268 | ForEach-Object {
        $tick++
        ($_.directreports) | foreach-object {
           # Output the current Object information, uses ad-object just in case a contact is used
            Get-ADobject -identity $_ -Properties manager,SamAccountName -server contoso.net:3268 | Select-Object -Property Name, SamAccountName, DistinguishedName, @{ L = "Manager"; E = { (Get-Aduser -identity $_.manager -server contoso.net:3268).samaccountname }}, @{ L = "Level"; E = {$tick} }
            if ($tick -le $count) {
                # Find the DirectReports of the current item
                Get-ADdirectReports -SamAccountName $_
            }
        }
    }
}
Get-ADdirectReports carters 2

答案 1 :(得分:0)

我的答案不多,但这个很有意思

&#34;#找到当前项目的直接报告&#34;只有samaccountname而不是count;因此计数默认为0 :)

尝试:

 # Find the DirectReports of the current item 
Get-ADdirectReports -SamAccountName $_ $count