Import-Module ActiveDirectory
# Path to create users in
$path = "OU=TestUser,OU=Test,DC=Test,DC=com"
# Connection string to SQL Server database
$connectionString = "Server=WIN8\SQLEXPRESS;Database=DBA_Utilities;Trusted_Connection=yes;"
# Select statement to return new user accounts
# Needs to return "sAMAccountName" & "Password" columns
# Note: Other columns names should match AD attribute name
$sql = "Select FirstName as GivenName,
LastName as sn,
DisplayName as DisplayName,
samAccountName as sAMAccountName,
EmailAddress as mail,
City as l,
Department as Department,
StreetAddress as StreetAddress,
State as st,
samAccountName+'@test.com' as userPrincipalName,
PostalCode as postalcode,
MobilePhone as mobile,
OfficePhone as telephoneNumber,
Department as department,
Title as Title,
Office as physicalDeliveryOfficeName,
Country as co,
'Abc-123456' as Password
from GetActiveDirectoryUsers where Action = 'yes' "
###########################
$cn = new-object system.data.sqlclient.sqlconnection
$cn.ConnectionString = $connectionString
$cn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = $sql
$cmd.connection = $cn
$dr = $cmd.ExecuteReader()
$colCount = $dr.FieldCount
$sAMAccountNameOrdinal = $dr.GetOrdinal("sAMAccountName")
$PasswordOrdinal = $dr.GetOrdinal("Password")
while ($dr.Read())
{
# Get value of sAMAccountName column
$sAMAccountName = $dr.GetValue($sAMAccountNameOrdinal)
# Get value password column (converted to secure string for New-ADUser Cmdlet)
$password = ConvertTo-SecureString -AsPlainText $dr.GetValue($PasswordOrdinal) -Force
write-host "Creating user account..." $sAMAccountName
$otherAttributes = New-Object System.Collections.HashTable
# Create a hash table of attribute names and attribute values
# Used to populate other attributes.
for ($i = 0; $i -le $colCount - 1; $i++)
{
$attribute = $dr.GetName($i)
switch ($attribute)
{
"Password"{ } #Ignore
"SAMAccountName" { } #Ignore
default
{
$otherAttributes.Add($attribute, $dr.GetValue($i))
}
}
}
# Create Active Directory User Account
New-ADUser -sAMAccountName $sAMAccountName -Name $DisplayName -Path $path -otherAttributes $otherAttributes -Enable $true -AccountPassword $password
}
$dr.Close()
$cn.Close()
Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.
”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.
Our community of experts have been thoroughly vetted for their expertise and industry experience.
The Distinguished Expert awards are presented to the top veteran and rookie experts to earn the most points in the top 50 topics.