Sharing is caring, right? Here is a powershell script I wrote that creates new users based on their First name and surname, checks to see if a username exists from their first name in AD, if it does append the first letter from their surname and use that as their username, if that exists, append the next letter, etc. I also have logic to set and create the user’s home drive, add the account to the correct security groups, create a remote mailbox, begin a delta sync on Azure AD Connect, log to a text file for audit purposes and print off a word document to pass on details to new user.

#New Staff Account Creation Script, Created by NCK - Last Revised 14/05/2018</code>

#DECLARED VARIABLES

$Colours = "Boris", "Doris", "Moris", "Loris"

$RandomColour = Get-Random $Colours

$RandomNumber = Get-Random -Minimum 100 -Maximum 999

$FirstPassword = -join ($RandomColour,"00",$RandomNumber)

Write-Host "**********************************************************"

Write-Host "New Staff Login Creation Script"

Write-Host "Please follow the instructions as follows:"

Write-Host "**********************************************************"

$First =Read-Host "Enter First Name"

$Last =Read-Host "Enter Surname"

$Initials=Read-Host "Enter Initials (First Letter of First Name and First and Last Letter of Surname"

$Title =Read-Host "Job Title (Optional)"

$StaffType=Read-Host "Make an Admin Staff (type 1),Teaching Staff (type 2), Governors (type 3), Invigilators (Type 4)"

$AccountExpiryDate=Read-Host "Enter Expiry Date"

$HomeDriveLetter = "F:"

$SamAccountName = $First + $Last.Substring(0,0).ToLower()

$Filter = $First + '*'

$SimilarUsers = @( Get-ADUser -Filter {proxyAddresses -Like $Filter} -ErrorAction SilentlyContinue | Select-Object SamAccountName )

#do an if statement to check if username already exists in AD, if it does do an else and add a character to the surname e.g "Bob Smith" Would be bobs and if "bobs" exists it'll be "bobsm"

if ($SamAccountName -notin $SimilarUsers.proxyAddresses + "@contoso.ac.uk") {

#return $SamAccountName

New-ADUser "$First $Last" -SamAccountName $SamAccountName -GivenName $First -Surname $Last -DisplayName "$First $Last" -Path 'OU=Staff,OU=Staff Users,DC=contoso,DC=local' -PasswordNeverExpires $false -Department $Dept -Title $Title -Company "Carmel College" -EmailAddress $SamAccountName'@contoso.ac.uk' -Initials $Initials -UserPrincipalName $SamAccountName'@contoso.ac.uk'

}

else {

$i = 1

while ($SamAccountName -in $SimilarUsers.proxyAddresses + "@contoso.ac.uk") {

if ($i -eq $Last.Length + 1) {

throw "No Available Usernames."

}

$SamAccountName = $First + $Last.Substring(0,$i)

$i++

#return $SamAccountName

New-ADUser "$First $Last" -SamAccountName $SamAccountName -GivenName $First -Surname $Last -DisplayName "$First $Last" -Path 'OU=Staff,OU=Staff Users,DC=contoso,DC=local' -PasswordNeverExpires $false -Department $Dept -Title $Title -Company "Company Name" -EmailAddress $SamAccountName'@contoso.ac.uk' -Initials $Initials -UserPrincipalName $SamAccountName'@contoso.ac.uk'

}

}

Write-Host "a new username named $SamAccountName is about to be created"

$HomeDrivePath = "\\fileserver\UserHomeFolders\$SamAccountName"

#Flick the AD Object to Enabled

#Set the Password on the AD Object to the one that was randomly generated in the #FirstPassword Variable

Start-Sleep -s 5

Set-ADAccountPassword -Identity $SamAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $FirstPassword -Force) -ErrorAction SilentlyContinue

Enable-ADAccount -Identity $SamAccountName -ErrorAction SilentlyContinue

Set-ADAccountExpiration -Identity $SamAccountName -DateTime $AccountExpiryDate

Start-Sleep -s 5

#Set the HomeDrive Letter and HomeDirectory attributes on the AD Object

Set-ADUser -Identity $SamAccountName -HomeDrive $HomeDriveLetter -HomeDirectory $HomeDrivePath -ChangePasswordAtLogon $true

#Add the User to the Printer Users and Staff_Users Security Groups

Get-ADUser $SamAccountName | Add-ADPrincipalGroupMembership -MemberOf "Print Users"

Get-ADUser $SamAccountName | Add-ADPrincipalGroupMembership -MemberOf "Staff_Users"

#If 1 then add user to the Admin Security Group and move to Admin Staff OU, if 2 add user to Teaching Staff Security Group Group and move to Teaching Staff OU

switch ($StaffType)

{

'1' {

Get-ADUser $SamAccountName| Move-ADObject -TargetPath 'OU=Admin Staff,OU=Staff,OU=Staff Users,DC=contoso,DC=local'

Get-ADUser $SamAccountName | Add-ADPrincipalGroupMembership -MemberOf Admin

}

'2' {

Get-ADUser $SamAccountName| Move-ADObject -TargetPath 'OU=Teaching Staff,OU=Staff,OU=Staff Users,DC=contoso,DC=local'

Get-ADUser $SamAccountName | Add-ADPrincipalGroupMembership -MemberOf Teachers

}

'3' {

Get-ADUser $SamAccountName| Move-ADObject -TargetPath 'OU=Governors,OU=Staff,OU=Staff Users,DC=contoso,DC=local'

}

'4' {

Get-ADUser $SamAccountName| Move-ADObject -TargetPath 'OU=Invigilators,OU=Staff,OU=Staff Users,DC=contoso,DC=local'

}

}

$homeShare = New-Item -path $HomeDrivePath -ItemType Directory -force -ea Stop

$acl = Get-Acl $homeShare

$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"

$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow

$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"

$PropagationFlags = [System.Security.AccessControl.PropagationFlags]::None

$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($SamAccountName, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)

$acl.AddAccessRule($AccessRule)

Set-Acl -Path $homeShare -AclObject $acl -ea Stop

$ExchangeServer = "mailserver"

# Import session for Exchange and Create a Remote Mailbox (New Staff are in O365)

$SO = New-PSSessionOption -SkipCACheck -SkipRevocationCheck -SkipCNCheck

$ExchSession = New-PSSession -ConfigurationName Microsoft.Exchange -SessionOption $SO -ConnectionUri http://$ExchangeServer/powershell -Authentication Kerberos -AllowRedirection

Import-PSSession $ExchSession

Enable-RemoteMailbox $SamAccountName -RemoteRoutingAddress $SamAccountName'@contoso.mail.onmicrosoft.com'

$AADConnectSvr = "AADConnectServer"

# Import session for Azure AD Connect and Run a Delta Sync

$AADsession=New-PSSession -ComputerName $AADConnectSvr

#Import-PSSession $AADsession

Invoke-Command -Session $AADsession {

Start-ADSyncSyncCycle -PolicyType Delta

}

#Logging - Audit Purposes - Log what computer made the account, what logged in user who ran the script. "User created by: $LoggedInUser on $ComputerName for: $First $Last $SamAccountName $FirstPassword

$LogFilePath="\\managementserver\its\Powershell\logs\"

$LogFileName="StaffCreation.log"

$NewLine = -join ("`r`n$(get-date -f yyyy-MM-dd-ss) - A New Staff Account was created by $env:UserName on $env:ComputerName for $First $Last - username is $SamAccountName and Password is $FirstPassword")

Add-Content -Value $NewLine -Path "$LogFilePath$LogFileName"

Write-Host $NewLine

$word=new-object -ComObject "Word.Application"

$doc=$word.documents.Add()

$word.Visible=$True

$selection=$word.Selection

$selection.TypeParagraph()

$selection.TypeText(("A new staff user account has been made for $First $Last"))

$selection.TypeParagraph()

$selection.TypeText(("Username: $SamAccountName"))

$selection.TypeParagraph()

$selection.TypeText(("Password: $FirstPassword"))

$selection.TypeParagraph()

$selection.TypeText(("Your email address will be $SamAccountName@contoso.ac.uk"))

$selection.TypeParagraph()

$selection.TypeText(("When you first login you will be asked to reset your password. Your password must be at least 8 characters long and MUST contain at least one capital letter and at least one number"))

$word.PrintOut()

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.