I've been piecing this together little by little for a little over a week. I'm curious if there's a cleaner way to accomplish what this is doing. Basically, it's pulling data from a CSV, creating some variables and generating a user in AD and adding the user to various groups. The script works: the data is scraped from the CSV and the user is created and added to various groups. The logging works to a point but I can't seem to replicate an outright failure. If the user already exists, there's not much you can do - in my testing.
The logging, in my opinion, makes things quite ugly/cumbersome but in some respects, I'd like to have it more verbose and just give me details - pass or fail. Furthermore, I feel like the adding of users to the groups could be handled better.
# CSV file being imported.
$CsvFile = "$env:USERPROFILE\Downloads\SampleData.csv"
# Import the contents of the CSV file.
$Users = Import-Csv -Path "$CsvFile"
# Logs will be dumped here.
$LogFolder = "C:\Temp"
# Setting up an array for holding results.
$UserCreationSuccess = @()
$UserCreationFailure = @()
$UsersAlreadyExist = @()
#$GroupJoinSuccess = @()
$VerbosePreference = "Continue"
# Loop through each line of the CSV, creating variables for each field.
ForEach ($User in $Users) {
# Creating the basic variables.
$FirstName = $User.'Student First Name'
$MiddleInitial = $User.'I'
$LastName = $User.'Student Last Name'
$ADUserName = $User.'Stu Access Login'
$StudentID = $User.'Other ID'
$GradYear = $User.'Grad Year'
$CapFInitial = $FirstName.substring(0,1).ToUpper()
$MInitial = $MiddleInitial.substring(0,1).ToLower()
$LInitial = $LastName.substring(0,1).ToLower()
$Password = "$CapFInitial$MInitial$LInitial" + "#" + "$StudentID"
# The folowing couple variables are created via Switch statements.
$SchoolCode = Switch ($User.'School')
{
20 { "Exeter Township Senior High" }
30 { "Exeter Township Junior High" }
40 { "Lorane Elementary School" }
50 { "Jacksonwald ES" }
70 { "Reiffton School" }
90 { "Owatin Creek Elementary School" }
}
$ADGroups = Switch ($User.'School')
{
20 { "Secondary Students", "Students" }
30 { "Secondary Students", "Students" }
40 { "K4 Students", "Students" }
50 { "K4 Students", "Students" }
70 { "Secondary Students", "Students" }
90 { "K4 Students", "Students" }
}
# Headers for the CSV exported later.
$ExportCsvProperties = @{
FirstName = $FirstName;
LastName = $LastName;
UserName = $ADUserName;
Error = $Null;
Date = (Get-Date)
}
If (-Not(Get-ADUser -Filter {SamAccountName -eq $ADUserName})) {
Try {
# Create user.
New-ADUser `
-Name "$FirstName $LastName" `
-SamAccountName "$ADUserName" `
-GivenName "$FirstName" `
-Initials "$MiddleInitial" `
-Surname "$LastName" `
-DisplayName "$FirstName $MiddleInitial. $LastName" `
-UserPrincipalName "[email protected]" `
-EmailAddress "[email protected]" `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
-Enabled $false `
-PasswordNeverExpires $true `
-CannotChangePassword $true `
-Path "OU=$GradYear,OU=Students,OU=$SchoolCode,OU=accounts,DC=academic,DC=mydomain,DC=com"
# If you've gotten this far, the user has been created; output to screen.
Write-Verbose "[PASS] Created [$($ADUserName)]."
# Add SUCCESS data to the array.
$UserCreationSuccess += New-Object -TypeName PSCUSTOMOBJECT -Property $ExportCsvProperties
# Add user to group(s).
ForEach ($ADGroup in $ADGroups) {
# Add user to group.
Get-ADUser -Identity $ADUserName | Add-ADPrincipalGroupMembership -MemberOf $ADGroup
# Output to the screen
Write-Verbose "[PASS] Added [$($ADUserName)] to [$($ADGroup)]."
# Add SUCCESS data to the array for successful join.
#$GroupJoinSuccess += New-Object -TypeName PSCUSTOMOBJECT -Property $ExportCsvProperties
} # End ForEach
} # End Try
Catch {
#Write-Error "[ERROR] Can't create user [$($ADUserName)] : $_"
Write-Error "[ERROR] Can't create user [$($ADUserName)] : $($_.Exception.Message)"
# Collect FAILURE data for the array.
$ExportCsvProperties.error = $($_.Exception.Message)
# Add FAILURE data to the array.
$UserCreationFailure += New-Object -TypeName PSCUSTOMOBJECT -Property $ExportCsvProperties
} # End Catch
} # End IF
Else {
Write-Warning "The account [$($ADUserName)] wasn't created, it already exists."
$UsersAlreadyExist += New-Object -TypeName PSCUSTOMOBJECT -Property $ExportCsvProperties
} # End Else
} # End ForEach
If (-Not(Test-Path $LogFolder)) {
Write-Verbose "Folder [$($LogFolder)] does not exist, creating"
New-Item $LogFolder -Force
}
# Export data in the array to CSV.
$UserCreationSuccess | Export-Csv -Path "$LogFolder\UserCreationSuccess.csv" -NoTypeInformation -Append
$UserCreationFailure | Export-Csv -Path "$LogFolder\UserCreationFailure.csv" -NoTypeInformation -Append
$UsersAlreadyExist | Export-Csv -Path "$LogFolder\UsersAlreadyExist.csv" -NoTypeInformation -Append
#$GroupJoinSuccess | Export-Csv -Path "$LogFolder\GroupJoinSuccess.csv" -NoTypeInformation -Append