#Define SIMS Server details $SIMSServer = "SIMSSERVER\SQLINSTANCE" $SIMSDatabase = "SIMS" $SIMSUser = "SIMSUser" $SIMSPassword = "SIMSPassword" #Define SIMS report name and export location $ReportName = "SIMS Staff Report" $ReportLocation = "z:\UserReport\CrayfordStaff.csv" #Define email details $SMTPServer = "1.2.3.4" $SMTPPort = "25" $From = "noreply@domain.com" $To = "itservices@domain.com" $CC = "hr@domain.com" Import-Module ActiveDirectory function SetFolderPermissions { $Cluster = $args[0] $Cluster $PossibleUserName = $args[1] $PossibleUserName $HomeDirPath = $args[2] $HomeDirPath $User = "$($Cluster)\$($PossibleUserName)" $User $Rights = "Read, ReadAndExecute, ListDirectory, Modify, Write" #Comma seperated list. $InheritSettings = "Containerinherit, ObjectInherit" #Controls how permissions are inherited by children $PropogationSettings = "None" #Usually set to none but can setup rules that only apply to children. $RuleType = "Allow" #Allow or Deny. $acl = Get-Acl $HomeDirPath $perm = $User, $Rights, $InheritSettings, $PropogationSettings, $RuleType $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $perm $acl.SetAccessRule($rule) $acl | Set-Acl -Path $HomeDirPath } function CreateUser { $Cluster = $args[0] $School = $args[1] $PreferredForename = $args[2] $PreferredSurname = $args[3] $LegalForename = $args[4] $LegalSurname = $args[5] $DOB_Number = $args[6] $UPN = $args[7] $Teacher = $args[8] $Department = $args[9] $JobTitle = $args[10] if ($School -eq $null) {$School = "HACA"} if ($School -eq " ") {$School = "HACA" } if ($School -eq "CTG - North") {$School = "CTGNC"} if ($School -eq "CTG - South") {$School = "CTGSC"} if ($Teacher -eq "T") { $JobType = "Teaching" } if ($Teacher -eq "F") { $JobType = switch ($JobTitle) { "Admin" {"Administrative"} "Administraion" {"Administrative"} "Administration" {"Administrative"} "Attendance" {"Administrative"} "Catering" {"Administrative"} "CCF" {"Administrative"} "Cleaning Team" {"Administrative"} "Design and Art" {"Teaching Support"} "English" {"Teaching Support"} "Facilities" {"Administrative"} "Federation Support" {"Administrative"} "HTG" {"Teaching Support"} "I.T." {"IT Services"} "Inclusion" {"Teaching Support"} "IT" {"IT Services"} "IT Services" {"IT Services"} "LSA" {"Teaching Support"} "Maths" {"Teaching Support"} "MFL" {"Teaching Support"} "Midday Meals" {"Teaching Support"} "Music" {"Teaching Support"} "Premises/Security/Transport" {"Administrative"} "Primary" {"Teaching Support"} "School Staff Instrutctor" {"Teaching Support"} "Science" {"Teaching Support"} "Sixth Form" {"Teaching Support"} "Support" {"Teaching Support"} "Support Staff" {"Teaching Support"} "Support Staff/Technicians" {"Teaching Support"} "Supported Learning" {"Teaching Support"} "Volunteer" {"Teaching Support"} "Admin/Music" {"Administrative"} "Admissions" {"Administrative"} "Art & Design" {"Teaching Support"} "Art Department" {"Teaching Support"} "Cover" {"Teaching Support"} "DT" {"Teaching Support"} "Examinations" {"Administrative"} "Exams" {"Administrative"} "Inclusion/Safeguarding" {"Teaching Support"} "KS4/5" {"Teaching Support"} "Learning Support" {"Teaching Support"} "LRC" {"Teaching Support"} "Pre School" {"Teaching Support"} "Premises" {"Administrative"} "Primary Support" {"Teaching Support"} "Reprograhics" {"Administrative"} "Safeguarding and Inclusion" {"Teaching Support"} "Science/Service Staff" {"Teaching Support"} "Service Staff" {"Administrative"} "Exams" {"Teaching Support"} "Facilities Management" {"Administrative"} "Finance" {"Administrative"} "Health and Social Care" {"Teaching Support"} "Human Resources" {"Administrative"} "ICT Services" {"IT Services"} "P.E" {"Teaching Support"} "Pastoral" {"Teaching Support"} "PE" {"Teaching Support"} "Reprographics" {"Administrative"} "SEN" {"Teaching Support"} "SEN - Inclusion" {"Teaching Support"} "Welfate" {"Teaching Support"} default {"Administrative"} } } $UserID = $School + $UPN $ReturnedObject = New-Object System.Object #Choose which DC we're going to use to create the users on. Choosing a specific DC to avoid issues with replication if ($Cluster -eq "Clus1") {$DC = "dc.clus1.internal.domain.com"} if ($Cluster -eq "Clus2") {$DC = "dc.clus2.internal.domain.com"} #Set school specific options if ($School -eq "School1") {$SchoolAddress = "School Address with lines seperated`r`nby the backticks"; $SchoolCity = "City"; $SchoolPostCode = "Postcode";$CompanyName = "School Name"} if ($School -eq "School2") {$SchoolAddress = "School Address with lines seperated`r`nby the backticks"; $SchoolCity = "City"; $SchoolPostCode = "Postcode";$CompanyName = "School Name"} $ReturnedObject | Add-Member -MemberType NoteProperty -Name "Cluster" -Value $Cluster $ReturnedObject | Add-Member -MemberType NoteProperty -Name UPN -Value $UserID #Check if a user with this UPN already exists $DoesUPNExist = Get-ADUser -Filter {EmployeeNumber -eq $UserID } -Server $dc #If it doesn't, create the user if ($DoesUPNExist -eq $null) { #Choose which file server we're going to put the user's user area into if ($School -eq "School1") {$FileServer = "School1FileServer.school1.internal.domain.com\staff$"} if ($School -eq "School2") {$FileServer = "School2FileServer.school1.internal.domain.com"} #Generate Possible Username $PossibleUserName = $PreferredForename.Substring(0,1) + "." + $PreferredSurname #Check Username for spaces if ($PossibleUserName -like '* *') { #Remove space if present $PossibleUserName = $PossibleUserName -replace ' ', '' } #Check Username for apostrophe if ($PossibleUserName -like "*'*") { #Remove apostrophe if present $PossibleUserName = $PossibleUserName -replace "'", '' } #Check Username for hyphen if ($PossibleUserName -like "*-*") { #Remove hyphen if present $PossibleUserName = $PossibleUserName -replace "-", '' } #If the username is more than 19 characters, truncate it if ($PossibleUserName.Length -gt 19) { $PossibleUserName = $PossibleUserName.Substring(0,19) } #Check for duplicate $CreateTest = Get-ADUser -Filter {sAMAccountName -eq $PossibleUserName } -Server dc.clus1.internal.domain.com $CreateTest = $CreateTest + (Get-ADUser -Filter {sAMAccountName -eq $PossibleUserName } -Server dc.clus2.internal.domain.com) #If duplicate found, put a number on the end and test again. Keep Incrementing until a unique value is found if ($CreateTest -ne $null) { Clear-Variable CreateTest $Count=0 do { $Count++ $DupeCheck = $PossibleUserName + $Count $CreateTest = Get-ADUser -Filter {sAMAccountName -eq $PossibleUserName } -Server dc.clus1.internal.domain.com $CreateTest = $CreateTest + (Get-ADUser -Filter {sAMAccountName -eq $PossibleUserName } -Server dc.clus2.internal.domain.com) if ($CreateTest -eq $null) {$Count = 999} } Until ($Count -eq 999) $PossibleUserName = $DupeCheck } $ReturnedObject | Add-Member -MemberType NoteProperty -Name "UserName" -Value $PossibleUserName #Generate our unique-ish password $Password = "Password" + $DOB_Number $PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force #Create the account #$ResultsTextArea.AppendText( + "Password for User: " + $Password + "`r`n" $ReturnedObject | Add-Member -MemberType NoteProperty -Name Password -Value $Password #Where is the user object going? $OUPath = "OU=$($JobType) Staff,OU=Staff,OU=Users,OU=$($School),OU=$($Cluster),DC=$($Cluster),DC=domain,DC=com" #$ResultsTextArea.AppendText( + "OU Path for User: " + $OUPath + "`r`n" $ReturnedObject | Add-Member -MemberType NoteProperty -Name OUPath -Value $OUPath #Set the DisplayName $Displayname = $PreferredForename.substring(0,1) + " " + $PreferredSurname $ReturnedObject | Add-Member -MemberType NoteProperty -Name DisplayName -Value $Displayname New-ADUser -AccountPassword $PasswordSecure ` -CannotChangePassword $false ` -ChangePasswordAtLogon $true ` -PasswordNeverExpires $false ` -GivenName $PreferredForename ` -Surname $PreferredSurname ` -Name $PossibleUserName ` -DisplayName $Displayname ` -EmailAddress "$($PossibleUserName)@haaf.org.uk" ` -Enabled $true ` -Path $OUPath ` -UserPrincipalName "$($PossibleUserName)@haaf.org.uk" ` -EmployeeNumber $UserID ` -StreetAddress $SchoolAddress ` -PostalCode $SchoolPostCode ` -City $SchoolCity ` -Department $Department ` -Company $CompanyName ` -Title $JobTitle ` -Server $DC Set-ADUser -Identity $PossibleUserName -Server $DC -add @{extensionAttribute1=$LegalSurname} Set-ADUser -Identity $PossibleUserName -Server $DC -add @{extensionAttribute2=$LegalForename} Set-ADUser -Identity $PossibleUserName -Server $DC -add @{extensionAttribute14="Staff"} Set-ADUser -Identity $PossibleUserName -Server $DC -add @{extensionAttribute15="Licensed"} #Add user to intake group Get-ADGroup -Identity "$($School) $($JobType) Staff" -Server $DC | Add-ADGroupMember -Members $PossibleUserName -Server $DC #Set the user's homefolder attributes and create the user's user area on the school file server #Set the user's home folder path $HomeDirPath = "\\$($FileServer)\$($PossibleUserName)" #$ResultsTextArea.AppendText( + "User's Home Directory Path: " + $HomeDirPath + "`r`n" $ReturnedObject | Add-Member -MemberType NoteProperty -Name HomePath -Value $HomeDirPath #Set the homedir and homedrive parameters in user account Set-ADUser -Identity $PossibleUserName -Server $DC -HomeDrive N: -HomeDirectory $HomeDirPath #Create the folder New-Item -Path $HomeDirPath -ItemType Directory | Out-Null $ReturnedObject | Add-Member -MemberType NoteProperty -Name Note -Value "Account Created" Clear-Variable DoesUPNExist } else { $ReturnedObject | Add-Member -MemberType NoteProperty -Name UserName -Value $DoesUPNExist.SamAccountName $ReturnedObject | Add-Member -MemberType NoteProperty -Name Password -Value "" $ReturnedObject | Add-Member -MemberType NoteProperty -Name OUPath -Value "" $ReturnedObject | Add-Member -MemberType NoteProperty -Name DisplayName -Value "" $ReturnedObject | Add-Member -MemberType NoteProperty -Name HomePath -Value "" $ReturnedObject | Add-Member -MemberType NoteProperty -Name Note -Value "Duplicate" } return $ReturnedObject Clear-Variable UserID } # end CreateUser function #Main program #Generate CSV File from SIMS #Run SIMS report and save it to the appropriate place & "C:\Program Files (x86)\SIMS\SIMS .net\CommandReporter.exe" /user:$($SIMSUser) /password:$($SIMSPassword) /report:"$($ReportName)" /output:$($ReportLocation) /servername:$($SIMSServer) /databasename:$($SIMSDatabase) #Import CSV $UserDetails = import-csv $ReportLocation #Set School and Cluster $Cluster = "Crayford" #Set Logfiles $Logfile = "z:\staffreport\$(([datetime](get-date)).ToString("yyyyMMdd_HHmm"))_Creation_Report.log" $AccountsCreated = "z:\staffreport\$(([datetime](get-date)).ToString("yyyyMMdd_HHmm"))_Accounts_Created_Report.csv" #Create Logfiles New-Item $Logfile -ItemType File -Value "User creation results for $(Get-date)" New-Item $AccountsCreated -ItemType File -Value "Accounts created on $(Get-date)`r`n" #Define array for saving results $Global:ResultsToSave = @() #Loop through CSV and create user accounts $UserDetails | foreach { #Convert stupid SIMS date to proper date $DOB_Number = [datetime]$_.DOB #Add leading zeros to UPN $UPN = [int]$_.UPN $TextBoxEntry = CreateUser $Cluster $_.School $_.PreferredForename $_.PreferredSurname $_.LegalForename $_.LegalSurname $DOB_Number.ToString("ddMMyy") $UPN.ToString("00000") $_.TeachingStaff $_.Department $_.JobTitle if ($TextBoxEntry.Note -eq "Account Created") { #Add to log file Add-Content $Logfile("Username generated for $($_.PreferredForename) $($_.PreferredSurname): $($TextBoxEntry.Username)") Add-Content $Logfile("User's Password: $($TextboxEntry.Password)") Add-Content $Logfile("User's UPN: $($TextboxEntry.UPN)") Add-Content $Logfile("Cluster Created In: $($Cluster)") Add-Content $Logfile("School Created In: $($_.School)") Add-Content $Logfile("OU Path: $($TextBoxEntry.OUPath)") Add-Content $Logfile("Home Directory Path: $($TextboxEntry.HomePath)") #Output to console Write-Output("Username generated for $($_.PreferredForename) $($_.PreferredSurname): $($TextBoxEntry.Username)") Write-Output("User's Password: $($TextboxEntry.Password)") Write-Output("User's UPN: $($TextboxEntry.UPN)") Write-Output("Cluster Created In: $($Cluster)") Write-Output("School Created In: $($_.School)") Write-Output("OU Path: $($TextBoxEntry.OUPath)") Write-Output("Home Directory Path: $($TextboxEntry.HomePath)") } else { Add-Content $Logfile("A user for $($_.PreferredForename) $($_.PreferredSurname) with the UPN $($UPN) already exists") Write-Output("A user for $($_.PreferredForename) $($_.PreferredSurname) with the UPN $($UPN) already exists") } $Global:ResultsToSave += $TextBoxEntry } Write-Output("Sleeping") Start-Sleep(60) Write-Output("Waking and setting permissions") #Set permissions $Global:ResultsToSave | foreach { if ($_.Note -eq "Account Created") { SetFolderPermissions $_.Cluster $_.UserName $_.HomePath Write-Output ("Home folder permissions for $($_.Username) set") Add-Content $Logfile ("Home folder permissions for $($_.Username) set") } else { Write-Output ("$($_.Username) is a duplicate user, skipping setting permissions") Add-Content $Logfile ("$($_.Username) is a duplicate user, skipping setting permissions") } } $Global:ResultsToSave | Where-Object {$_.Note -eq "Account Created"} | ConvertTo-Csv -NoTypeInformation | Add-Content $AccountsCreated $ResultsToEmail = $ResultsToSave | where-object {$_.Note -ne "Duplicate"} if ($ResultsToEmail -ne $null) { $Subject = "New User Accounts generated on $(([datetime](get-date)).ToString("dd/MM/yyyy"))" $Attachment = $AccountsCreated $Body = "Hello, Some new network accounts have been created after being entered on SIMS. Please find the log file with the username and initial password for the new member of staff attached. Thanks, IT Support" Send-MailMessage -From $From -to $To -Subject $Subject -Attachments $Attachment -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort }