active directory - Powershell - User creation script avoid duplicate username -
i ad search using powershell discover if username want create in use,. if in use want script add following number @ , of user name.
import-module activedirectory $family= mclaren $first= tony #this part of script use first 5 letters of $family , first 2 letters of $first , join them give $username of 7 letters $username = $family.substring(0, [math]::min(5, $family.length)) + $first.substring(0, [math]::min(2, $first.length))
- the user name "mclarto" base on (username take 5 first letters of family name plus 2 charof firstname) seach done in ad.
- if there no result, "mclarto" taken $username without number @ end.
- if search find other users same username, username should take following number, in case "mclarto1".
- if "mclarto1" exist "mclarto2" should use , on.
the answer have propose david martin there, there part if username don't exist, i don't want $username contain number if it's unique.
thanks
i think close, uses activedirectory module.
import-module activedirectory $family = "mclaren*" # users matching search criteria $matchingusers = get-aduser -filter 'userprincipalname -like $family' if ($matchingusers) { # array of usernames splitting on @ symbol $matchingusers = $matchingusers | select -expandproperty userprincipalname | %{($_ -split "@")[0]} # loop around each user extracting numeric part $usernumbers = @() $matchingusers | % { if ($_ -match '\d+') { $usernumbers += $matches[0] } } # find maximum number $maxusernumber = ($usernumbers | measure-object -max).maximum # store result adding 1 along way (probably worth double checking doesn't exist) $suggestedusername = $family$($maxusernumber+1) } else { # no matches use name $suggestedusername = $family } # display results write-host $suggestedusername
Comments
Post a Comment