Create bulk users in AD - Simple, using ADSI
Hello,
I thought I'd share one of the scripts I used while working on a customer scenario. I needed to create lot of users on a particular OU. I've used below script to create bulk users to fulfil that scenario:
#Get the connection.
$domain = [ADSI]"LDAP://RootDSE"
$domain_DN = $domain.Get("defaultNamingContext")
$localhost = $env:computername + ":389"
$domain_conn = [ADSI] "LDAP://$localhost/$domain_DN";
## For new OU
$readOU = read-host "What will be the name of new OU under $domain_DN ? Please take care of OU name restrictions and put in quotes if with space"
$ouList = $domain_conn.psbase.get_children()
$ouExists = $false
foreach ($mem in $ouLis)
{
if($mem.name -eq $readOU)
{ $ouExists = $true;
write-host "OU $readOU found - already exists"
}
}
if(!$ouExists)
{
$newOU = $domain_conn.Create("organizationalUnit", "ou=$readOU");
$newOU.SetInfo();
}
else
{
write-host "wow! $readOU is a good name for an OU, users will be created in this OU"
}
##For new Users in new OU
$ouPath = "ou=" + $readOU+"," + $domain_DN
$ou_conn= [ADSI] "LDAP://$localhost/$ouPath"
write-host "`nA prefix will be used to create number of users entered appending each number at the end. i.e. if the prefix is 'jadoo-' then users will be created as 'jadoo-0', 'jadoo-1', 'jadoo-2'.. and so on."
$prefix = read-host "`nWhat is the prefix for username?"
[int]$limit = read-host "`nHow many users do you want to create? "
$pass = read-host "`nEnter a common password for users"
for($i=0; $i -lt $limit; $i++)
{
$userName = $prefix + $i;
$userCN = "cn=" + $userName;
$objUser = $ou_conn.Create("user", $userCN);
$objUser.Put("sAMAccountName", $userName);
$objUser.SetInfo();
$objUser.SetPassword($pass)
$objUser.psbase.InvokeSet("AccountDisabled", $false);
$objUser.SetInfo();
}
## display OU and users created
$ou_conn
$ou_conn.psbase.get_children() | select distinguishedName
I hope this will be helpful for those wanting to quickly create bulk users for testing some scenario in Lab.