2013-05-02 187 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