I'm trying to create a script that will read a CSV full of users to create. It will then create the users and generate them random passwords, it then needs to send me an email with all of the created users and all of their corresponding passwords along with the original CSV. My current script doesn't work correctly and the problems are described below.
The script currently doesn't work very well at all. There are five test users in the CSV and all it manages to do is create the first user and doesn't do that correctly. There is no first name or display name. Neither is it created in the set group, and it's disabled. It then sends the email with the CSV but doesn't give me the one user is has created, it just gives me all of the errors. I have a feeling that if this does work that it will create using the same password for each user, it needs to be unique.
$filePath = “D:\myfilepath\ScriptTestUsers.csv”
# Import the CSV file containing the user information
$users = Import-Csv $filePath
# Create an empty array to store the created users with their passwords
$createdUsers = @()
# Create an empty array to store the users that couldn't be created and the errors
$errorUsers = @()
# Loop through each user in the CSV file
foreach ($user in $users) {
$firstname = $user.'FirstName' # Get the firstname from the CSV file
$lastname = $user.'LastName' # Get the lastname from the CSV file
$username = $user.'UserName' # Get the username from the CSV file
# Check if the 'UserName' field is empty, if so, add the user to the error array and continue to the next iteration
if (!$username) {
$error = "Missing 'UserName' field for a user in the CSV file, skipping."
$errorUsers += "$username $error"
continue
}
# Check if the user already exists in AD, if so, add the user to the error array and continue to the next iteration
if (Get-ADUser -Identity $username -ErrorAction SilentlyContinue) {
$error = "User $username already exists in AD, skipping."
$errorUsers += "$username $error"
continue
}
$ou = $user.'OU' # Get the OU from the CSV file
# Check if the specified OU exists, if not, add the user to the error array and continue to the next iteration
if (!(Get-ADOrganizationalUnit -Identity $ou -ErrorAction SilentlyContinue)) {
$error = "OU $ou does not exist, skipping."
$errorUsers += "$username $error"
continue
}
$groups = $user.'Groups' # Get the groups from the CSV file
# Check if the specified group(s) exists, if not, add the user to the error array and continue to the next iteration
if ($groups) {
$missingGroups = $groups | Where-Object { !(Get-ADGroup -Identity $_ -ErrorAction SilentlyContinue) }
if ($missingGroups) {
$error = "Group(s) $missingGroups do not exist, skipping."
$errorUsers += "$username $error"
continue
}
}
$expiry = $user.'ExpiryDate' # Get the account expiry date from the CSV file
$description = $user.'Description' # Get the description from the CSV file
# Generate a random password
$password = [System.Web.Security.Membership]::GeneratePassword(16, 2)
#$email = "<[email protected]>"
# Create the AD user and add them to the specified groups
try {
New-ADUser -Name $firstname -Surname $lastname -SamAccountName $username -UserPrincipalName $username -Path $ou -Description $description -AccountExpirationDate $expiry -PassThru | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString $password -AsPlainText -Force)
if ($groups) {
Add-ADGroupMember -Identity $groups -Members $username -ErrorAction Stop
}
# Add the user and their password to the array of created users
$createdUsers += "$username $password"
} catch {
$error = $_.Exception.Message
$errorUsers += "$username $error"
}
}
# Create the HTML body of the email with CSS styling
$body = "<html><head><style>body { background-color: lightblue; font-family: calibri;}</style></head><body>Successfully Created Users:<br>" + ($createdUsers -join "<br>") + "<br><br>Users that couldn't be created and the errors:<br>" + ($errorUsers -join "<br>") + "</body></html>"
# Send the email with the list of created users and their passwords and attach the original CSV file
$DateSh = (Get-Date).ToString("yyyyMMdd")
#Email options
$options = @{
'SmtpServer' = "relay"
'To' = "<[email protected]>"
'From' = "SERVER1 <server1@domain>"
'Subject' = "$DateSh-NewUsersCreated"
'BodyAsHtml' = $true
'Attachments' = $filePath
}
#Send email
Send-MailMessage @options -Body $Body
The Errors I receive after it has run are:
Get-ADUser : Cannot find an object with identity: 'ScriptTestUser001' under: 'DC=mydc'
Get-ADGroup : Cannot find an object with identity: 'Group1, Group2' under: 'DC=mydc'
Cannot overwrite variable Error because it is read-only or constant.
Please help.
To check if the user exists you can use:
For the groups, you cannot just pass a string with all the group separated with commas and spaces, you need to split it into an array first:
Regarding the account being disabled after creation that's normal you did not provide the password when creating the user (this is documented here)
And yes as mentioned by @vonPryz the
$Error
variable is reserved (this is documented here).