#Import the PowerShell module containing AD CMDLETS
Import-Module ActiveDirectory
#Read a CSV File with the User or Group details and create an account in AD for each entry
Function Create-ADAccountsFromCSV {
Param (
[parameter(Mandatory=$true)][string]$CSVPath,
[parameter(Mandatory=$true)][string]$Type,
[parameter(Mandatory=$true)][string]$OrgUnit
)
if (($Type -ne "Group") -and ($Type -ne "User"))
{
Throw New-Object System.ArgumentException("Type parameter must be specified as either 'User' or 'Group'.")
}
#Read the CSV File
$csvData = Import-Csv $CSVPath
foreach ($line in $csvData) {
#Create a hash table of the account details
$accountTable = @{
'givenName'=$line.FirstName
'sn'= $line.LastName
'displayName'= $line.DisplayName
'sAMAccountName'= $line.sAMAccountName
'password' = $line.Password
'description' = $line.Description
'office' = $line.Office
'officephone' = $line.Phone
'emailaddress' = $line.Email
'streetaddress' = $line.Address1
'pobox' = $line.Address2
'city' = $line.City
'state' = $line.County
'postalcode' = $line.Postcode
'department' = $line.Department
'company' = $line.Company
'group1' = $line.Group1
'group2' = $line.Group2
'ou' = $OrgUnit
}
if ($Type -eq "User")
{
#Call the function to create a User Account
CreateUser -AccountInfo $accountTable
}
if ($Type -eq "Group")
{
#Call the function to create a Group Account
CreateGroup -AccountInfo $accountTable
#Get New Group
$groupFilterString = "samAccountName -like `"" + $line.sAMAccountName + "`""
$group = Get-ADGroup -Filter $groupFilterString
#Walk through each member column associated with this group
$memberColumnNumber = 1
$memberColumn = "Member" + $memberColumnNumber
#While a member column still exists, ad the value to a Group
while ($line.$memberColumn)
{
#Check if User is already a member of the Group
$member = Get-ADGroupMember $group | Where { $_.samAccountNmae -eq $line.$memberColumn }
#If not already a member of the Group, add the User to the Group
IF ($member -eq $null)
{
Write-Host "Adding" $line.$memberColumn "as a Member of the Group" $group.Name
try
{
$userFilterString = "samAccountName -like `"" + $line.$memberColumn + "`""
$user = Get-ADUser -Filter $userFilterString
Add-ADGroupMember -Identity $group -Members $user
}
Catch
{
Write-Host "There was a problem adding" $line.$memberColumn "as a member to the Group" $group.Name "-" $_ -ForegroundColor Red
}
}
ELSE
{
Write-Host "User" $line.$memberColumn "was not added to the Group" $group.Name "as this User was already a member of that Group" -ForegroundColor Blue
}
$memberColumnNumber = $memberColumnNumber + 1
$memberColumn = "Member" + $memberColumnNumber
}
}
}
}
#Create an Active Directory User
Function CreateUser {
Param($AccountInfo)
TRY
{
#Check to see if the User Account already exists
$userFilterString = "samAccountName -like `"" + $AccountInfo['sAMAccountName'] + "`""
$user = Get-ADUser -Filter $userFilterString
#If User Account does not already exist, create it
Function CopyFrom {
$GroupBool = Read-Host "Copy group membership from existing user? Y/N. Default is N"
if ($GroupBool.ToLower() -eq "y"){
$UserToCopyFrom = Read-Host "Enter the user account to copy from."
return (Get-ADUser $UserToCopyFrom -Properties MemberOf).MemberOf
}
}
cls
$Name = Read-Host "Enter the User Name for the New User"
$Groups = CopyFrom
#This is a very basic account creation. You should probably set Surname, First Name, Full Name, Department, etc. Tailor this to your environment.
if ($user -eq $null)
{
Write-Host "Creating User Account:" $AccountInfo['sAMAccountName']
#Create the user account object
New-ADUser -SamAccountName $AccountInfo['sAMAccountName'] `
-Name $AccountInfo['displayName'] `
-DisplayName $AccountInfo['displayName'] `
-GivenName $AccountInfo['givenName'] `
-Surname $AccountInfo['sn'] `
-Path $AccountInfo['ou'] `
-Office $AccountInfo['office'] `
-OfficePhone $AccountInfo['officephone'] `
-EmailAddress $AccountInfo['emailaddress'] `
-StreetAddress $AccountInfo['streetaddress'] `
-POBox $AccountInfo['pobox'] `
-State $AccountInfo['state'] `
-PostalCode $AccountInfo['Postalcode'] `
-City $AccountInfo['City'] `
-Title $AccountInfo['description'] `
-Department $AccountInfo['department'] `
-Company $AccountInfo['company'] `
-ChangePasswordAtLogon $true `
-AccountPassword (ConvertTo-SecureString $AccountInfo['password'] -AsPlainText -Force) `
-Description $AccountInfo['description'] `
-Enabled $true
#Set "User must change password" to TRUE after User has been created.
#For some reason, if you set to TRUE above it doesn't work - presumably a bug
#To set this option to TRUE, de-comment the 2 lines below (remove the hashtag symbols)
# $user = Get-ADUser -Filter $userFilterString
# Set-ADUser $user -ChangePasswordAtLogon $true
}
ELSE
{
Write-Host "User" $AccountInfo['sAMAccountname'] "was not created as this User Account already exists" -ForegroundColor Cyan
}
}
CATCH
{
Write-Host "There was a problem creating a User Account:" $AccountInfo['sAMAccountName'] "-" $_ -ForegroundColor Red
}
#This will be empty if the user opted not to copy existing membership.
ForEach ($g in $groups){
#This adds the group membership after the account is created.
Add-ADGroupMember $g $name
}
#NOTE: YOU MUST RUN "PREPARE TO CREATE USERS AND GROUPS FROM CSV.PS1" BEFORE YOU RUN THIS SCRIPT
#IF YOU GET THE ERROR:
#Create-ADAccountsFromCSV : The term 'Create-ADAccountsFromCSV' is not recognized as the name of
#a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
# was included, verify that the path is correct and try again.
#THEN YOU'VE NOT RUN THAT COMMAND FIRST!!!!!
#Create Users from the CSV File in C:\CSVs\NewUsers.csv - you need to edit the OrgUnit entry.
#EXAMPLE:
#Create-ADAccountsFromCSV -CSVPath "C:\CSVs\NewUsers.csv" -OrgUnit "OU=Staff,OU=Users,OU=Waterloo Lodge,OU=Education,DC=ACE,DC=Local" -Type "User"
Create-ADAccountsFromCSV -CSVPath "C:\CSVs\NewUsers.csv" -OrgUnit "OU=Users,OU=OFFICE,OU=OU,DC=DOMAIN,DC=Local" -Type "User"
Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.
When asked, what has been your best career decision?
Deciding to stick with EE.
Being involved with EE helped me to grow personally and professionally.
Connect with Certified Experts to gain insight and support on specific technology challenges including:
We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE