2016-06-17 27 views
1

因此,这里的工作不正是我试图做的:PowerShell的While循环如预期

我手动输入一个名字,然后我想谁的名字我输入的人下工作的用户列表( extensionattribute9是用户在其下工作的人)。但是,对于在该人员下工作的每个人,我也想为他们运行该流程,并查看是否有人也在他们之下工作。我希望这个过程继续下去,直到没有人在当前用户下工作。

我已经做了3次这样做,没有一个while循环,但是因为我不知道要得到每个人有多深,我觉得使用while循环会更好整体,尤其是在代码长度方面。

这里是我目前拥有的代码:

$users = Get-ADUser -Filter * -Properties extensionattribute9,Displayname,mail,title 

$users | ForEach-Object { 
if ($_.extensionattribute9 -like '*Lynn, *') 
{ 
     $_ | select Displayname,userprincipalname,title,extensionattribute9 
     $name = $_.Displayname 

     while ($_.extensionattribute9 -ne $null){ $users | ForEach-Object { 
      if ($_.extensionattribute9 -eq $name) 
      { 
      $_ | select Displayname,userprincipalname,title,extensionattribute9 
      $name=$_.Displayname 
      } 
    } 
    }   
} 
} 

当我运行下的Lynn“我得到一个用户(用户A)的代码,然后在用户A的用户在此之后,没事。该程序仍然继续运行,但没有返回。我猜它陷入了一个无限循环,但我不知道把while循环放在哪里更好。帮帮我?

回答

0

这听起来像你正在尝试做的嵌套而递归搜索/换每一个可以结束严重的循环。你可以尝试这样的事情:

Function Get-Manager { 

    param([Object]$User) 

    $ManagerName = $User.extensionattribute9 

    # Recursion base case 
    if ($ManagerName -eq $null){ 
     return 
    } 

    # Do what you want with the user here 
    $User | select Displayname, userprincipalname, title, extensionattribute9 

    # Recursive call to find manager's manager 
    $Manager = Get-ADUser -Filter "Name -like $ManagerName" 
    Get-Manager $Manager 

} 

# Loop through all ADusers as you did before 
$Users = Get-ADUser -Filter * -Properties extensionattribute9,Displayname,mail,title 

Foreach ($User in $Users) { 
    Get-Manager $User 
} 

请注意,我没有使用PowerShell与Active Directory所以语法可能是不正确的经验,但不应该是很难解决。希望这可以帮助!

0

我对Powershell并不熟悉,但您遇到问题的一个可能原因是$_被用来表示两种不同的事情,具体取决于您是否在while循环中使用它。 Powershell真的很聪明,知道你的意思吗?

更重要的是:代码

$_ | select Displayname,userprincipalname,title,extensionattribute9 
    $name = $_.Displayname 

出现在两个地方并拢。这是一种确定的代码味道。它应该只出现一次。

当您遍历一个层次结构并且您不知道它将会走多深时,您必须使用递归算法(一种自我调用的函数)。这是伪代码:

function myFunc ($node) { 
    //report the name of this node 
    echo "node $node found." ; 
    // check to see if this node has any child nodes 
    array $children = getChildNodes ($node) ; 
    if (count($children) == 0) { 
     //no child nodes, get out of here 
     return ; 
    } 
    //repeat the process for each child 
    foreach($children as $child) { 
     myFunc($child) ; 
    } 
}