#CHS User Creation Script #Version 0.1 function checkForLicense($user, [string] $sku) { foreach ($lic in $user.Licenses) { if ($lic.AccountSkuId -eq $sku) { return $true } } return $false } Function Reconnect-ExchangeOnline { if ($EOLSession.state -eq 'Broken' -or !$EOLSession) {Disconnect-ExchangeOnline; Start-Sleep -Seconds 1; Connect-ExchangeOnline} } Function Connect-ExchangeOnline { Param( [parameter()] $Credential = $Global:OnlineCred ) Write-Host "Connecting to Exchange Online" $Global:EOLSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Credential -Authentication Basic -AllowRedirection Write-Host "Importing Exchange Online Module" $Global:EOLModule = Import-Module (Import-PSSession $Global:EOLSession -DisableNameChecking -AllowClobber) -Global -PassThru -DisableNameChecking } Function Disconnect-ExchangeOnline { $Global:EOLModule | Remove-Module -Force $Global:EOLSession | Remove-PSSession Get-PSSession | Where-Object {$_.ComputerName -like '*.outlook.com'} | Remove-PSSession } Function New-FileShare { #this function returns $True is the share is successfully created Param([string]$computername=$env:computername, [string]$path=$(Throw "You must enter a complete path relative to the remote computer."), [string]$share=$(Throw "You must enter the name of the new share."), [string]$comment ) #Username/Group to give permissions to $trustee = ([wmiclass]'Win32_trustee').psbase.CreateInstance() $trustee.Domain = $null $trustee.Name = "EVERYONE" #Accessmask values $fullcontrol = 2032127 $change = 1245631 $read = 1179785 #Create access-list $ace = ([wmiclass]'Win32_ACE').psbase.CreateInstance() $ace.AccessMask = $fullcontrol $ace.AceFlags = 3 $ace.AceType = 0 $ace.Trustee = $trustee #Securitydescriptor containting access $sd = ([wmiclass]'Win32_SecurityDescriptor').psbase.CreateInstance() $sd.ControlFlags = 4 $sd.DACL = $ace $sd.group = $trustee $sd.owner = $trustee $FILE_SHARE = 0 $connections = $null #uncomment this next line for debugging # Write-Host ("Creating share {0} for {1} on {2} ({3})" -f $share,$path,$computername,$comment) -fore Green [wmiclass]$wmishare="\\$computername\root\cimv2:win32_share" $return=$wmishare.Create($path,$share,$FILE_SHARE,$null,$comment, "", $sd) Switch ($return.returnvalue) { 0 {$rvalue = "Success"} 2 {$rvalue = "Access Denied"} 8 {$rvalue = "Unknown Failure"} 9 {$rvalue = "Invalid Name"} 10 {$rvalue = "Invalid Level"} 21 {$rvalue = "Invalid Parameter"} 22 {$rvalue = "Duplicate Share"} 23 {$rvalue = "Redirected Path"} 24 {$rvalue = "Unknown Device or Directory"} 25 {$rvalue = "Net Name Not Found"} } if ($return.returnvalue -ne 0) { Write-Warning ("Failed to create share {0} for {1} on {2}. Error: {3}" -f $share,$path,$computername,$rvalue) return $False } else { return $True } } # , 7, 8, 9,10,11,12,13 $usermapping = 0,1,2,3,4,5,6,17,16,15,14,13,12,11,10 $missingusers = @() $disabledusers = @() cd \chsu Write-Progress -activity "Running" -status "Looking for SIMS" -PercentComplete 0 $path = "c:\Program Files (x86)\sims\sims .net\CommandReporter.exe" Write-Progress -Activity "Starting" -Status "Starting background staff report" -PercentComplete 1 $arguments = '/USER:"xxxx" /PASSWORD:"xxxxx" /REPORT:"Staff Details Update" /QUIET /OUTPUT:"c:\chsu\staff.xml"' $processStartInfo = New-Object System.Diagnostics.ProcessStartInfo; $processStartInfo.FileName = $path; $processStartInfo.WorkingDirectory = (Get-Location).Path; $processStartInfo.Arguments = $arguments $processStartInfo.UseShellExecute = $false; $process2 = [System.Diagnostics.Process]::Start($processStartInfo); Write-Progress -activity "Running" -status "Running Student Report" -PercentComplete 2 $arguments = '/USER:"xxxxx" /PASSWORD:"xxxx" /REPORT:"User Details Update" /QUIET /OUTPUT:"c:\chsu\students.xml"' $processStartInfoS = New-Object System.Diagnostics.ProcessStartInfo; $processStartInfoS.FileName = $path; $processStartInfoS.WorkingDirectory = (Get-Location).Path; $processStartInfoS.Arguments = $arguments $processStartInfoS.UseShellExecute = $false; $process = [System.Diagnostics.Process]::Start($processStartInfoS); $process.WaitForExit(); Write-Progress -Activity "Running" -Status "Getting users" -PercentComplete 3 $base="OU=Students,OU=xxx,OU=Establishments,DC=xxxx,DC=internal" $su = Get-ADUser -searchbase $base -filter 'employeeID -like "*"' -Properties memberof, employeeNumber, employeeID, displayName, sn, description, department, departmentNumber, company, userPrincipalName, givenName, photo, jpegPhoto, thumbnailPhoto, mail, proxyAddresses, extensionAttribute3 Write-Progress -Activity "Connecting to MSOnline" -PercentComplete 4 Import-Module msonline $powerUser = "office365@xxxxxx.onmicrosoft.com" $password = ConvertTo-SecureString -String 'xxxxx' -AsPlainText -Force $adminCredential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $powerUser,$password $Global:OnlineCred = $adminCredential Connect-MSOLService -Credential $adminCredential Connect-ExchangeOnline -Credential $adminCredential Write-Progress -activity "Processing" -status "Processing Students.xml" -PercentComplete 5 [xml]$students = Get-Content c:\chsu\students.xml $xc = $students.SuperStarReport.Record.Count $x = 0 $ns = 0 $newstu = "" foreach ($s in $students.SuperStarReport.Record) { $x++ $i = 5 + ($x / $xc * 70) Write-Progress -activity "Processing" -status "Processing Students.xml $i% ($x / $xc)" -PercentComplete $i $found = $false $name = $s.Name foreach ($u in $su) { if ($u.extensionAttribute3 -eq $s.ID) { $found = $true $sam = $u.SamAccountName if ($s.On_x0020_roll -eq "Y") { if ($s.Enrolment_x0020_status -eq "Single Registration") { $des = $s.Name + " in " + $s.Reg Set-ADUser $u -EmployeeID $s.UPN -EmployeeNumber $s.Adno -Company "xxxx High School" -Surname $s.Surname -GivenName $s.Forename -DisplayName $s.Name -Description $des -Department $s.Reg try { Set-ADUser $u -Replace @{departmentNumber=$s.Year_x0020_taught_x0020_in_x0020_Code } } catch { Write-Host $s.Year_x0020_taught_x0020_in_x0020_Code -ForegroundColor Green Set-ADUser $u -Add @{departmentNumber=$s.Year_x0020_taught_x0020_in_x0020_Code } } if ($s.Parental_x0020_Consent) { if ($u.MemberOf -like "CN=No Internet*") { Remove-ADGroupMember -Identity "No Internet" -Members $u.Name -Confirm:$false } } else { if ([int]$s.Year_x0020_taught_x0020_in_x0020_Code -lt 10) { if ($u.MemberOf -notlike "CN=No Internet*") { Add-ADGroupMember -Identity "No Internet" -Members $u.Name -Confirm:$false } } } } else { $des = $s.Name + " [Collab]" Set-ADUser $u -EmployeeNumber $s.Adno -Company "xxxx High School" -Surname $s.Surname -GivenName $s.Forename -DisplayName $s.Name -Description $des -Department "Collabrative" } if ($s.SelectSingleNode("photo")) { $b = [System.Convert]::FromBase64String($s.Photo) Set-ADUser $u -Replace @{thumbnailPhoto=$b } Set-ADUser $u -Replace @{photo=$b } Set-ADUser $u -Replace @{jpegPhoto=$b } } if ($u.UserPrincipalName.Contains(".internal")) { $upm = $u.UserPrincipalName.Replace("xxxx.internal", "students.xxxx.sch.uk") Set-ADUser $u -UserPrincipalName $upn -EmailAddress $upn $n = $u.SamAccountName ForEach ($proxyAddress in $u.ProxyAddresses) { if ($proxyAddress -like "SMTP") { Set-ADUser $u -Remove @{proxyaddresses=$proxyAddress} } } Set-ADUser $u -Add @{proxyaddresses="smtp:$n@xxxx.mail.onmicrosoft.com" } Set-ADUser $u -Add @{proxyaddresses="SMTP:$upn" } } $msolu = Get-MsolUser -UserPrincipalName $u.UserPrincipalName if ($msolu.IsLicensed) { } else { $msolu.UsageLocation = "GB" Set-MsolUser -UserPrincipalName $u.UserPrincipalName -UsageLocation "GB" } if(checkForLicense -user $msolu -sku "xxx:STANDARDWOFFPACK_IW_STUDENT") { } else { Set-MsolUserLicense -UserPrincipalName $u.UserPrincipalName -AddLicenses "xxx:STANDARDWOFFPACK_IW_STUDENT" Start-Sleep -Seconds 1; } <#Reconnect-ExchangeOnline if (-not (Get-MailboxPermission -Identity $u.UserPrincipalName -User admin@xxxx.sch.uk)) { Reconnect-ExchangeOnline Add-MailboxPermission -Identity $u.UserPrincipalName -AccessRights FullAccess -User "admin@xxxx.sch.uk" -Confirm:$false -InheritanceType All –Automapping $False } Reconnect-ExchangeOnline if (-not (Get-MailboxPermission -Identity $u.UserPrincipalName -User it@xxxx.sch.uk)) { Reconnect-ExchangeOnlineReconnect-ExchangeOnline Add-MailboxPermission -Identity $u.UserPrincipalName -AccessRights FullAccess -User "it@xxxx.sch.uk" -Confirm:$false -InheritanceType All –Automapping $False }#> Write-Host "Updated $sam $name" } elseif ($s.On_x0020_roll -eq "N") { if ($u.Enabled -eq $true) { $dt = [DateTime]$s.Leaving_x0020_Date $ts = New-TimeSpan -Days 60 $dn = (get-date) - $ts if ($dt -lt $dn) { Disable-ADAccount $u.SamAccountName $mu = Get-MsolUser -UserPrincipalName $u.UserPrincipalName foreach ($lic in $mu.Licenses) { Set-MsolUserLicense -UserPrincipalName $u.UserPrincipalName -RemoveLicenses $lic.AccountSkuId } $disabledusers += ,$u Write-Host -ForegroundColor Yellow "Disabled Off Roll User $sam $name" } else { Write-Host -ForegroundColor DarkYellow "User taken off roll but not exceeded 60 days $sam $name $dt $dn" } } } break } } if ($found -eq $false) { if ($s.On_x0020_roll -eq "Y") { $d = $name if ($s.Student_x0020_Status -eq "Pre-admission") { if ($s.Reg -and $s.UPN) { $d = $s.Reg $des = $s.Name + " in " + $s.Reg Write-Host -ForegroundColor Red "Not found '$des'- Creating Pre-Admission" [int]$ygn = [convert]::ToInt32($s.Reg.Split(' ')[0]) $intake = $usermapping[$ygn] $BaseUsername = ($intake.ToString() + $s.Forename.Substring(0,1) + $s.Surname.Substring(0, 1)) $username = $BaseUsername $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} -Server svr-002 if($ADUser) { $ok = $false $x1 = 0; while ($ok -eq $false) { $x1++ $username = $BaseUsername + $x1 $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} if($ADUser) { $ok = $false } else { $ok = $true } } } $password = ConvertTo-SecureString -String 'password' -AsPlainText -Force $path = "OU=Intake $intake,OU=Students,OU=xxxx,OU=Establishments,DC=xxx,DC=internal" $p2 = "\\svr-002\RMStudentWork\Intake $intake\$username" $profile = "\\svr-002\RMStudentProfiles\Intake $intake\$username" $d = "H:\Students\Work\Intake $intake\$username" New-ADUser -Server svr-002 -Name $username -SamAccountName $username -UserPrincipalName "$username@students.xxxx.sch.uk" -Enabled $true -Department $s.Reg -EmailAddress "$username@students.xxxx.sch.uk" -AccountPassword $password -Company "xxxx High School" -ChangePasswordAtLogon $true -Surname $s.Surname -GivenName $s.Forename -DisplayName $s.Name -Description $des -EmployeeID $s.UPN -EmployeeNumber $s.Adno -HomeDirectory "\\svr-002\$username$" -HomeDrive "N:" -Path $path -OtherAttributes @{proxyaddresses="SMTP:$username@students.xxxx.sch.uk";departmentNumber=$ygn;extensionAttribute3=$s.ID} -ProfilePath $profile Start-Sleep -s 4 Add-ADGroupMember -Identity "xxx Standard {UT}" -Server svr-002 -Members $username Add-ADGroupMember -Identity "xxx Students" -Server svr-002 -Members $username if ($s.Parental_x0020_Consent) { } else { Add-ADGroupMember -Identity "No Internet" -Members $u.Name } Set-ADUser $username -Add @{proxyaddresses="smtp:$username@xxxx.mail.onmicrosoft.com" } -server svr-002 New-Item -ItemType directory -Path $p2 New-Item -ItemType directory -Path $profile New-Item -ItemType directory -Path "$profile.v2" New-Item -ItemType directory -Path "$profile.v4" New-Item -ItemType directory -Path "$profile.v6" $Acl = Get-Acl "$profile" $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("xxxx\$username", "DeleteSubdirectoriesAndFiles, Write, ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", "ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl "$profile" $Acl Set-Acl "$p2" $Acl Set-Acl "$profile.v2" $Acl Set-Acl "$profile.v4" $Acl Set-Acl "$profile.v6" $Acl Set-ADUser -server svr-002 $username -ChangePasswordAtNextLogon $true New-FileShare -computername svr-002 -path "$d" -share "$username$" #set disk quota on user to 5gb #Invoke-Command -ComputerName SVR-002 -ScriptBlock { fsutil quota modify H: 1000000000 1073741824 $args[0] } -argumentlist "xxxx\$username" $ns++ $newstu += @" New Pre-Admission user created for $des Username $username Password 'password' "@ Write-Host -ForegroundColor Green "New Pre-admission Student created '$name'" } else { #ignore pre-admission user until reg is assigned Write-Host -ForegroundColor Yellow "Skipping Pre-admission student '$name' awaiting Reg Assignment" } } elseif ($s.Enrolment_x0020_Status -eq "Single Registration") { #Todo: create new user and email Claire Jones with username if ($s.UPN -and $s.Year_x0020_taught_x0020_in_x0020_Code) { $d = $s.Reg $des = $s.Name + " in " + $s.Reg Write-Host -ForegroundColor Red "Not found '$des'- Creating" $intake = $usermapping[$s.Year_x0020_taught_x0020_in_x0020_Code] Write-Host $intake -ForegroundColor DarkYellow $BaseUsername = ($intake.ToString() + $s.Forename.Substring(0,1) + $s.Surname.Substring(0, 1)) $username = $BaseUsername $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} -Server svr-002 if($ADUser) { $ok = $false $x1 = 0; while ($ok -eq $false) { $x1++ $username = $BaseUsername + $x1 $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} if($ADUser) { $ok = $false } else { $ok = $true } } } $password = ConvertTo-SecureString -String 'password' -AsPlainText -Force $path = "OU=Intake $intake,OU=Students,OU=xxx,OU=Establishments,DC=xxxx,DC=internal" $p2 = "\\svr-002\RMStudentWork\Intake $intake\$username" $profile = "\\svr-002\RMStudentProfiles\Intake $intake\$username" $d = "H:\Students\Work\Intake $intake\$username" New-ADUser -Server svr-002 -Name $username -SamAccountName $username -UserPrincipalName "$username@students.xxxx.sch.uk" -Enabled $true -Department $s.Reg -EmailAddress "$username@students.xxxx.sch.uk" -AccountPassword $password -Company "xxxx High School" -ChangePasswordAtLogon $true -Surname $s.Surname -GivenName $s.Forename -DisplayName $s.Name -Description $des -EmployeeID $s.UPN -EmployeeNumber $s.Adno -HomeDirectory "\\svr-002\$username$" -HomeDrive "N:" -Path $path -OtherAttributes @{proxyaddresses="SMTP:$username@students.xxxx.sch.uk";departmentNumber=$s.Year_x0020_taught_x0020_in_x0020_Code;extensionAttribute3=$s.ID} -ProfilePath $profile Start-Sleep -s 5 Add-ADGroupMember -Identity "xxx Standard {UT}" -Server svr-002 -Members $username Add-ADGroupMember -Identity "xxx Students" -Server svr-002 -Members $username if ($s.Parental_x0020_Consent) { } else { Add-ADGroupMember -Identity "No Internet" -Members $u.Name } Set-ADUser $username -Add @{proxyaddresses="smtp:$username@xxxx.mail.onmicrosoft.com" } -server svr-002 New-Item -ItemType directory -Path $p2 New-Item -ItemType directory -Path $profile New-Item -ItemType directory -Path "$profile.v6" $Acl = Get-Acl "$profile" $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("xxxx\$username", "DeleteSubdirectoriesAndFiles, Write, ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", "ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl "$profile" $Acl Set-Acl "$p2" $Acl Set-Acl "$profile.v6" $Acl Set-ADUser $username -server svr-002 -ChangePasswordAtNextLogon $true New-FileShare -computername svr-002 -path "$d" -share "$username$" #set disk quota on user to 5gb #Invoke-Command -ComputerName SVR-002 -ScriptBlock { fsutil quota modify H: 1000000000 1073741824 $args[0] } -argumentlist "xxxx\$username" $ns++ $newstu += @" New user created for $des Username $username Password 'password' "@ Write-Host -ForegroundColor Green "New Student created '$name'" } else { Write-Host -ForegroundColor Green "Student '$name' skipped due to missing UPN" } } elseif ($s.Enrolment_x0020_Status -eq "Subsidiary - Dual Registration" ) { if ($s.UPN -and $s.Year_x0020_taught_x0020_in_x0020_Code) { $des = $s.Name + " [Collab]" Write-Host -ForegroundColor Red "Not found '$des'- Creating" $intake = $usermapping[$s.Year_x0020_taught_x0020_in_x0020_Code] Write-Host $intake -ForegroundColor DarkYellow $BaseUsername = ($intake.ToString() + $s.Forename.Substring(0,1) + $s.Surname.Substring(0, 1)) $username = $BaseUsername $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} -Server svr-002 if($ADUser) { $ok = $false $x1 = 0; while ($ok -eq $false) { $x1++ $username = $BaseUsername + $x1 $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} if($ADUser) { $ok = $false } else { $ok = $true } } } $password = ConvertTo-SecureString -String 'password' -AsPlainText -Force $path = "OU=Intake $intake,OU=Students,OU=xxx,OU=Establishments,DC=xxxx,DC=internal" $p2 = "\\svr-002\RMStudentWork\Intake $intake\$username" $profile = "\\svr-002\RMStudentProfiles\Intake $intake\$username" $d = "H:\Students\Work\Intake $intake\$username" New-ADUser -Server svr-002 -Name $username -SamAccountName $username -UserPrincipalName "$username@students.xxxx.sch.uk" -Enabled $true -Department $s.Reg -EmailAddress "$username@students.xxxx.sch.uk" -AccountPassword $password -Company "xxxx High School" -ChangePasswordAtLogon $true -Surname $s.Surname -GivenName $s.Forename -DisplayName $s.Name -Description $des -EmployeeID $s.UPN -EmployeeNumber $s.Adno -HomeDirectory "\\svr-002\$username$" -HomeDrive "N:" -Path $path -OtherAttributes @{proxyaddresses="SMTP:$username@students.xxxx.sch.uk";extensionAttribute3=$s.ID} -ProfilePath $profile Start-Sleep -s 5 Add-ADGroupMember -Identity "xxx Standard {UT}" -Server svr-002 -Members $username Add-ADGroupMember -Identity "xxx Students" -Server svr-002 -Members $username if ($s.Parental_x0020_Consent) { } else { Add-ADGroupMember -Identity "No Internet" -Members $u.Name } Set-ADUser $username -Add @{proxyaddresses="smtp:$username@xxxx.mail.onmicrosoft.com" } -server svr-002 Set-ADUser $u -Add @{ extensionAttribute3=$s.ID } -server svr-002 New-Item -ItemType directory -Path $p2 New-Item -ItemType directory -Path $profile New-Item -ItemType directory -Path "$profile.v6" $Acl = Get-Acl "$profile" $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("xxxx\$username", "DeleteSubdirectoriesAndFiles, Write, ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", "ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl "$profile" $Acl Set-Acl "$p2" $Acl Set-Acl "$profile.v6" $Acl Set-ADUser $username -server svr-002 -ChangePasswordAtNextLogon $true New-FileShare -computername svr-002 -path "$d" -share "$username$" #set disk quota on user to 5gb #Invoke-Command -ComputerName SVR-002 -ScriptBlock { fsutil quota modify H: 1000000000 1073741824 $args[0] } -argumentlist "xxxx\$username" $ns++ $newstu += @" New user created for $des Username $username Password 'password' "@ Write-Host -ForegroundColor Green "New Student created '$name'" } else { Write-Host -ForegroundColor Green "Student '$name' skipped due to missing UPN" } } else { Write-Host -ForegroundColor Red "Not found '$name'" $missingusers += ,$s } } } } if ($ns -gt 0) { $subject = "New Users Created" $recp = "admin@xxxx.sch.uk", "it@xxxx.sch.uk", "itteach@xxxx.sch.uk", "itteach@xxxx.sch.uk" Send-MailMessage -SmtpServer "localhost" -Body $newstu -Subject $subject -From "it@xxxx.sch.uk" -To $recp } Write-Progress -Activity "Running" -Status "Getting staff users" -PercentComplete 75 $base="OU=xxx,OU=Establishments,DC=xxxx,DC=internal" $stu = Get-ADUser -searchbase $base -filter 'EmployeeNumber -like "*" -and ExtensionAttribute1 -like "*"' -Properties extensionAttribute1, employeeNumber, employeeID, displayName, sn, description, department, departmentNumber, company, userPrincipalName, givenName, mail, proxyAddresses Write-Progress -activity "Processing" -status "Processing Staff.xml" -PercentComplete 76 [xml]$staff = Get-Content c:\chsu\staff.xml $x = 0 $ns = 0 $newstaff = "" foreach ($s in $staff.SuperStarReport.Record) { $xc = $students.SuperStarReport.Record.Count $x++ $i = 76 + ($x / $xc * 23) Write-Progress -activity "Processing" -status "Processing Staff.xml $i% ($x / $xc)" -PercentComplete $i $found = $false $name = $s.Full_x0020_Name $dn = $s.Preferred_x0020_Forename + " " + $s.Preferred_x0020_Surname foreach ($u in $stu) { if ($u.employeeNumber -eq $s.ID) { $found = $true $sam = $u.SamAccountName Set-ADUser $u -EmployeeID $s.ID -Company "xxxx High School" -Surname $s.Preferred_x0020_Surname -GivenName $s.Preferred_x0020_Forename -DisplayName $dn -Description $dn Set-ADUser $u -Replace @{info=$name } $msolu = Get-MsolUser -UserPrincipalName $u.UserPrincipalName if ($msolu.IsLicensed) { } else { $msolu.UsageLocation = "GB" Set-MsolUser -UserPrincipalName $u.UserPrincipalName -UsageLocation "GB" } if (checkForLicense -user $msolu -sku "xxxx:STANDARDWOFFPACK_IW_FACULTY") { } else { Set-MsolUserLicense -UserPrincipalName $u.UserPrincipalName -AddLicenses "xxxx:STANDARDWOFFPACK_IW_FACULTY" Start-Sleep -Seconds 1; } Reconnect-ExchangeOnline if (-not (Get-MailboxPermission -Identity $u.UserPrincipalName -User nick@xxxx.sch.uk)) { Add-MailboxPermission -Identity $u.UserPrincipalName -AccessRights FullAccess -User "admin@xxxx.sch.uk" -Confirm:$false -InheritanceType All –Automapping $False } if (-not (Get-RecipientPermission -Identity $u.UserPrincipalName -Trustee it@xxxx.sch.uk)) { Add-RecipientPermission -Identity $u.UserPrincipalName -AccessRights SendAs -Trustee "it@xxxx.sch.uk" -Confirm:$false } Write-Host "Updated $sam $name" break } } if ($found -eq $false) { $BaseUsername = ($s.Preferred_x0020_Forename + $s.Preferred_x0020_Surname.Substring(0, 1)) $username = $BaseUsername $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} if($ADUser) { $ok = $false $x1 = 0; while ($ok -eq $false) { $x1++ $username = $BaseUsername + $x1 $ADUser = Get-ADUser -Filter {SamAccountName -eq $username} if($ADUser) { $ok = $false } else { $ok = $true } } } $password = ConvertTo-SecureString -String 'password' -AsPlainText -Force $path = "OU=Non-Teaching Staff,OU=xxx,OU=Establishments,DC=xxxx,DC=internal" $p2 = "\\svr-001\RMNonTeacherWork\$username" $profile = "\\svr-001\RMNonTeacherProfiles\$username" $d = "H:\RMUsers\Non-Teaching Staff\Work\$username" if ($s.Teaching_x0020_Staff -eq "T") { $path = "OU=Teaching Staff,OU=xxx,OU=Establishments,DC=xxxx,DC=internal" $p2 = "\\svr-001\RMTeacherWork\$username" $d = "H:\RMUsers\Teaching Staff\Work\$username" $profile = "\\svr-001\RMTeacherProfiles\$username" } New-ADUser -Name $username -server svr-001 -SamAccountName $username -UserPrincipalName "$username@xxxx.sch.uk" -Enabled $true -EmailAddress "$username@xxxx.sch.uk" -AccountPassword $password -Company "xxxx High School" -ChangePasswordAtLogon $true -DisplayName ($s.Preferred_x0020_Forename + " " + $s.Preferred_x0020_Surname) -Description ($s.Preferred_x0020_Forename + " " + $s.Preferred_x0020_Surname) -EmployeeID $s.ID -EmployeeNumber $s.ID -GivenName $s.Preferred_x0020_Forename -Surname $s.Preferred_x0020_Surname -HomeDirectory "\\svr-001\$username$" -HomeDrive "N:" -Path $path -OtherAttributes @{info=$name;proxyaddresses="SMTP:$username@xxxx.sch.uk";extensionAttribute1="Staff";extensionAttribute3=$s.ID} -ProfilePath $profile Start-Sleep -s 2 Add-ADGroupMember -server svr-001 -Identity "xxx Staff {UT}" -Members $username if ($s.Post_x0020_Reference -eq "Duty Manager") { Add-ADGroupMember -server svr-001 -Identity "xxx Sports Ce~1 {UT}" -Members $username Add-ADGroupMember -server svr-001 -Identity "xxx Sports Centre Staff" -Members $username } elseif ($s.Post_x0020_Reference -eq "Examination Invigilator") { Add-ADGroupMember -server svr-001 -Identity "xxx Examination Invigilators" -Members $username } else { if ($s.Teaching_x0020_Staff -eq "T") { Add-ADGroupMember -server svr-001 -Identity "xxx Teaching Staff" -Members $username } else { Add-ADGroupMember -server svr-001 -Identity "xxx Non-Teach Staff" -Members $username } } Set-ADUser $username -server svr-001 -Add @{proxyaddresses="smtp:$username@xxxx.mail.onmicrosoft.com" } Set-ADUser $username -server svr-001 -ChangePasswordAtNextLogon $true New-Item -ItemType directory -Path $p2 New-Item -ItemType directory -Path $profile New-Item -ItemType directory -Path "$profile.v6" $Acl = Get-Acl "$profile" $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("xxxx\$username", "DeleteSubdirectoriesAndFiles, Write, ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) $Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("CREATOR OWNER", "ReadAndExecute, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow") $Acl.SetAccessRule($Ar) Set-Acl "$profile" $Acl Set-Acl "$p2" $Acl Set-Acl "$profile.v6" $Acl New-FileShare -computername svr-001 -path "$d" -share "$username$" #set disk quota on user to 5gb Invoke-Command -ComputerName SVR-001 -ScriptBlock { fsutil quota modify H: 4294967296 5368709120 $args[0] } -argumentlist "xxxx\$username" $ns++ $newstaff += @" New staff user created for $name Username $username Password 'password' "@ Write-Host -ForegroundColor Green "New Staff created '$name'" } } if ($ns -gt 0) { $subject="New Staff Users Created" $recp = "admin@xxxx.sch.uk", "it@xxxx.sch.uk", "office@xxxx.sch.uk" Send-MailMessage -SmtpServer "localhost" -Body $newstaff -Subject $subject -From "it@xxxx.sch.uk" -To $recp } Disconnect-ExchangeOnline