2016-06-17 26 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) ; 
    } 
}