2013-05-02 70 views
0

我想使用PowerShell進行AD搜索,以發現我想創建的用戶名是否已被使用。如果它已經在使用中,我希望腳本在用戶名處添加以下數字。Powershell - 用戶創建腳本避免重複的用戶名

Import-Module ActiveDirectory 
    $family= Mclaren 
    $first= Tony 
    #This part of the script will use the first 5 letters of $family and the first 2 letters of $first and join them together to give the $username of 7 letters 
    $username = $family.Substring(0, [math]::Min(5, $family.Length)) + $first.Substring(0, [math]::Min(2, $first.Length)) 
  • 的用戶名會像上mclarto」鹼(用戶名 取姓加2的5個字母charof的姓名) 一個SEACH在AD完成。
  • 如果沒有結果,「mclarto」將被視爲$用戶名而不是 任何數字在最後。
  • 如果搜索找到其他用戶使用相同的用戶名,該用戶名 應採取下列數,在這種情況下,將 「mclarto1」
  • 如果「mclarto1」已經存在然後「mclarto2」應該使用等等。

我已經由大衛·馬丁提出的答案几乎是那裏,只有在如果用戶名不存在,我不想$用戶名包含一個號碼,如果它的獨特的一部分。

感謝

回答

2

我認爲這將讓你關閉,它使用ActiveDirectory模塊。 $ MatchingUsers = GET-ADUser便有-Filter '的UserPrincipalName樣 「$($家族)*」' 總是返回一個空搜索:

Import-Module ActiveDirectory 

$family = "Mclaren*" 

# Get users matching the search criteria 
$MatchingUsers = Get-ADUser -Filter 'UserPrincipalName -like $family' 

if ($MatchingUsers) 
{ 
    # Get an array of usernames by splitting on the @ symbol 
    $MatchingUsers = $MatchingUsers | Select -expandProperty UserPrincipalName | %{($_ -split "@")[0]} 

    # loop around each user extracting just the numeric part 
    $userNumbers = @() 
    $MatchingUsers | % { 
     if ($_ -match '\d+') 
     { 
      $userNumbers += $matches[0] 
     } 
    } 

    # Find the maximum number 
    $maxUserNumber = ($userNumbers | Measure-Object -max).Maximum 

    # Store the result adding one along the way (probably worth double checking it doesn't exist) 
    $suggestedUserName = $family$($maxUserNumber+1) 
} 
else 
{ 
    # no matches so just use the name 
    $suggestedUserName = $family 
} 

# Display the results 
Write-Host $suggestedUserName 
+0

嗨大衛,我無法通過AD搜索使用$ VAR得到。如果我使用正確的SamAccountName而不是$ var,我可以通過它。這是否可以使用Quest AD?或者以其他方式? – lotirthos227 2013-05-06 15:23:34

+0

我遇到了一個問題,如果SamAccountName已經存在,腳本就可以正常工作,但如果它是一個唯一的名稱,腳本總是返回Mclaren1的值,而不是返回Mclaren值,因爲它是唯一的結果。我希望我的解釋清楚。你認爲你可以幫忙搞清楚嗎? – lotirthos227 2013-05-06 18:52:13

+0

我已經更新了示例,通過刪除雙引號並將*放在變量中,看看是否有幫助? – 2013-05-07 08:05:27

相關問題