Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function New-Employee{
- <#
- .SYNOPSIS
- Opens a word doc in the path specified and grabs the User first and last name, the manager, the user to copy permissions and OU from, and the user job title. Verifies if a user account with the same SAMAccountName already exists and confirms the Username, Manager name, Permission copy user name and Job Title are correct through write host. There is also a switch to denote whether an email address is required. If email is not requird, the add email address portion is skipped. At the completion of the task, all performed actions will be displayed on screen.
- .DESCRIPTION
- Pulls data from New Hire word doc and creates useraccount and mailbox
- .PARAMETER FilePath
- Path to the new hire document for the user in question. Double quotes are required around the file path.
- .PARAMETER EmailRequired
- Denote whether the user requires an email address or not
- .PARAMETER UsageLocation
- Sets the license usage location for the user in Office365 CA (Canada), US (USA
- .PARAMETER LicenseType
- Sets license type to Enterprise or Standard
- .PARAMETER NoUserFolder
- Switch that indicates no user folder is required. Default action is to create a folder if this switch is not present
- .INPUTS
- .OUTPUTS
- .NOTES
- New-EmployeeV1 Created by Nick Smyth with the Windows Powershell ISE
- Update Version 1.7.1 - September 25, 2015 - Added User folder creation, Set-Acl's on folder and home drive mapping.
- Update Version 1.7.2 - November 19, 2015 - Added notification of parsing word doc. Remove special characters from names for UPN and SAM account name
- Added sleep of 10 seconds after folder creation.
- Update Version 1.7.3 - November 30, 2015 - Added -EmailAddressPolicyEnabled $false to line 296 "#Set Primary SMTP Address"
- Update Version 1.7.4 - December 21, 2015 - Check for exact match on UPN - Add switch to decline creating user folder
- Update Version 1.8 - May 27, 2016 - Added automated sending of welcome email to new users with email addresses
- .EXAMPLE
- New-Employee -FilePath "c:\temp\Newhire.docx"
- .EXAMPLE
- New-Employee -FilePath "c:\temp\Newhire.docx" -EmailRequired -UsageLocation CA -LicenseType Enterprise
- .EXAMPLE
- New-Employee -FilePath "c:\temp\Newhire.docx" -NoUserFolder
- .EXAMPLE
- New-Employee -FilePath "c:\temp\Newhire.docx" -NoUserFolder -EmailRequired -UsageLocation CA -LicenseType Enterprise
- #>
- [CmdletBinding()]
- Param (
- [Parameter(ParameterSetName = "Default",Mandatory,valueFromPipeline,Position=0)]
- [Parameter(ParameterSetName = "EmailRequired",Mandatory,valueFromPipeline,Position=0)]
- [String[]]$FilePath,
- [Parameter(ParameterSetName = "EmailRequired",Mandatory)]
- [Switch]$EmailRequired,
- [Parameter(ParameterSetName = "EmailRequired",Mandatory)]
- [ValidateSet("CA","US")]
- [string]$UsageLocation,
- [Parameter(ParameterSetName = "EmailRequired",Mandatory)]
- [ValidateSet("Standard","Enterprise")]
- [string]$LicenseType,
- [Parameter(ParameterSetName = "Default",valueFromPipeline,Position=0)]
- [Parameter(ParameterSetName = "EmailRequired",valueFromPipeline,Position=0)]
- [Switch]$NoUserFolder
- )
- $DocPath = "$FilePath"
- Write-output 'Parsing Word document and editing data, please wait...'
- #Open Word document
- $SearchArray = @('1. First Name:','2. Last Name:','3. Job Title:','4. Manager/Supervisor','User Name:')
- $Word = New-Object -ComObject Word.Application
- $Document = $Word.Documents.Open($DocPath)
- $CSVInfo = $Document.Paragraphs | ForEach-Object {
- foreach ($SearchText in $SearchArray) {
- $_.Range.Text | Where-Object {$_ -match $SearchText} | ForEach-Object {
- $_ -split ':' | Select-Object -Last 1
- }
- }
- }
- $word.quit()
- ##############################
- #All contents taken from Word Doc with spaces removed
- $Trim = $CSVInfo.trim()
- #New user information
- $Ufirstname = $Trim | select-object -Index 0
- if ($Ufirstname -like "*-*"){
- $UsamFirstname = $Ufirstname.Replace("-","")
- }
- else{
- $UsamFirstname = $Ufirstname
- }
- $Ulastname = $Trim | select-object -Index 1
- if (($Ulastname -like "*’*")){
- $UsamLastname = $Ulastname.Replace("’","")
- }
- else{
- $UsamLastname = $Ulastname
- }
- if ($Ulastname -like "*-*"){
- $UsamLastname = $Ulastname.Replace("-","")
- }
- else{
- $UsamLastname = $Ulastname
- }
- if ($Ulastname -like "* *"){
- $UsamLastname = $Ulastname.Replace(" ","")
- }
- else{
- $UsamLastname = $Ulastname
- }
- $UDetailedName= $Ulastname + ", " + $Ufirstname
- $UPN = $UsamFirstname + "." + $UsamLastname + "@domain.com"
- $Password = "123123!"
- #SAMAccountName Creation
- $i = 1
- Do { $Usam = ($Ufirstname.Substring(0,$i++).ToLower() + $Usamlastname.ToLower())
- Try {$exists = Get-ADUser -LDAPFilter "(sAMAccountName=$Usam)"}
- Catch { }
- }
- Until ($exists -eq $null)
- #Job Title
- $jtitle = $Trim | Select-Object -index 2
- #Test for exact match on user
- $testsam = $UsamFirstname.Substring(0,1) + $UsamLastname
- $exactmatch = Get-ADUser -filter {samaccountname -eq $testsam}
- ##############################
- #Manger Name
- $mname = ($trim | Select-Object -Index 3).split(" ")
- $Mfirstname = $mname | select-object -Index 0
- $Mlastname = $mname | select-object -Index 1
- if($Mlastname -like "*’*"){
- $Mlastname = $Mlastname.Replace("’","'")
- }
- $Mdisplayname = "$Mlastname" + ", " + "$Mfirstname"
- $Msam = Get-ADUser -Filter {Name -eq $Mdisplayname} | Select -ExpandProperty SamAccountName
- #User to copy group membership from
- $cname = ($trim | Select-Object -Index 4).split(" ")
- $Cfirstname = $cname | select-object -Index 0
- $Clastname = $cname | select-object -Index 1
- if($Clastname -like "*’*"){
- $Clastname = $Clastname.Replace("’","'")
- }
- $CDisplayName = "$Clastname" + ", " + "$Cfirstname"
- $Csam = Get-ADUser -filter {Name -eq $CDisplayName} | Select -ExpandProperty SamAccountName
- $ou = (get-aduser -Identity $Csam -Properties * | Select -ExpandProperty distinguishedname).split(",",3) | Select -Last 1
- ##############################
- #DATA VERIFICATION
- if ($EmailRequired)
- {
- #Verify SAMAccountName, UPN, Job Title, Manager and User to copy groups from
- Write-Output "Please verify the following information is correct" `n
- #Check for exact match of user
- if($exactmatch -eq $null){
- }else
- {
- Write-Output "There is already user with the username $($exactmatch.samaccountname) with the name $($exactmatch.name),"
- Write-Output 'Please verify this is not a duplicate user before proceeding'
- Read-Host 'Press Enter to continue or CTRL + C to exit.' `n
- }
- Write-Output "The username for $Ufirstname $Ulastname is $Usam"
- Write-Output "The UPN for $Ufirstname $Ulastname is $UPN"
- Write-Output "The job title for $Ufirstname $Ulastname is $jtitle"
- Write-Output "The Manager for $Ufirstname $Ulastname is $Msam"
- Write-Output "The user to copy permissions from is $Csam"
- #Verify Usage Location for Office365 License and License Type
- Write-Output "You have selected $UsageLocation, as the location for this user"
- Write-Output "You have selected $LicenseType, as the license for this user"
- Read-Host "If this information is correct, press Enter to continue or CTRL + C to exit."
- }
- Else
- {
- #Verify Job Title, Manager and User to copy groups from
- Write-Output "Please verify the following information is correct" `n
- #Check for exact match of user
- if($exactmatch -eq $null){
- }else
- {
- Write-Output "There is already user with the username $($exactmatch.samaccountname) with the name $($exactmatch.name),"
- Write-Output 'Please verify this is not a duplicate user before proceeding'
- Read-Host 'Press Enter to continue or CTRL + C to exit.' `n
- }
- Write-Output "The username for $Ufirstname $Ulastname is $Usam"
- Write-Output "The UPN for $Ufirstname $Ulastname is $UPN"
- Write-Output "The job title for $Ufirstname $Ulastname is $jtitle"
- Write-Output "The Manager for $Ufirstname $Ulastname is $Msam"
- Write-Output "The user to copy permissions from is $Csam"
- Read-Host "If this information is correct, press Enter to continue or CTRL + C to exit."
- }
- ##############################
- # ACTIVE DIRECTORY ACCOUNT CREATION
- #Create New User
- New-ADUser -Name $UDetailedname -SamAccountName $Usam -UserPrincipalName $upn -DisplayName $UDetailedName -GivenName $Ufirstname -Surname $Ulastname -Manager $Msam -Title $jtitle -Description $jtitle -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true -Path $ou
- #Copy Group Memberships
- Get-ADUser -Identity $Csam -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $usam
- ##############################
- # FOLDER CREATION, SET ACLS AND MAP HOME DRIVE - ADDED SEPT 25, 2015
- if($NoUserFolder){
- }
- Else{
- #user folder path
- $ufolder = "\\fileshare\users\"
- Write-Output 'Creating User folder and setting ACLs'
- #Create new user folder
- New-Item -Path $ufolder -Name $usam -ItemType Directory
- #Wait 15 seconds to before creating ACL
- Start-Sleep -Seconds 10
- #Set ACL on new user folder
- #Get current ACL of folder
- $Acl = Get-Acl "$ufolder$Usam"
- #Create Object with new permission rules
- $Ar = New-Object system.security.accesscontrol.filesystemaccessrule($Usam,"DeleteSubdirectoriesAndFiles, Modify, TakeOwnership, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow")
- #Set the access rule
- $Acl.SetAccessRule($Ar)
- #Apply to the folder
- Set-Acl "$ufolder$Usam" $Acl
- #Set Home Directory
- Set-Aduser -Identity $Usam -HomeDrive M: -HomeDirectory "$ufolder$Usam"
- }
- ##############################
- # CHECK FOR $EMAILREQUIRED SWITCH
- if($EmailRequired)
- {# If $EmailRequired switch exists
- #Login Loop that will verify Office365 credentials before proceeding
- $problem = $true
- while ($problem -eq $true) {
- try {#Open Connection to Office365
- Import-Module MSOnline
- #Admin Credential for O365
- $O365Cred = Get-Credential -message "Please enter your Office365 Admin credentials"
- #Create Remote session to office 365
- $O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection -ea Stop
- Write-Output 'Logon Successful. Please wait...'
- $problem = $false
- #Enter remote session to O365
- Import-PSSession $O365Session -AllowClobber
- Connect-MsolService –Credential $O365Cred
- }
- catch {
- Write-Output 'Your username or password was incorrect, please try again'
- }
- }#End Login verification loop
- ##############################
- #Run Manual DirSync - Custom built function
- Start-ADConnectDeltaSync
- #Waits to give Dirsync a chance to run before attempting mailbox creation
- Write-Output "Running Dirsync - No action required, creation of mailbox will start automatically"
- Start-Sleep -Seconds 30
- ##############################
- #ADD LICENSE AND USAGE LOCATION FOR OFFICE 365
- #Sets license type variable
- $LIC = "domain:" + "$LicenseType" + "pack";
- #Set usage location for license. CA=Canada, US=USA
- Set-MsolUser -UserPrincipalName $UPN -UsageLocation $UsageLocation
- #Update variable for the appropriate license type
- Set-MsolUserLicense -UserPrincipalName $UPN -AddLicenses $LIC
- #END ADD LICENSE AND USAGE LOCATION FOR OFFICE 365
- ##############################
- #CREATE REMOTE MAILBOX
- #Open connection to On Prem Exchange server
- $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeonprem/PowerShell/ -Authentication Kerberos -WarningAction:SilentlyContinue
- Import-PSSession $Session -AllowClobber
- #Set RemoteRoutingAddress variable
- $RRA = $UsamFirstname + "." + $UsamLastname + "@domain.mail.onmicrosoft.com"
- #Enable remote mailbox for user
- Enable-RemoteMailbox -Identity $UPN -RemoteRoutingAddress $RRA | Out-Null
- #Set Primary SMTP Address
- Set-RemoteMailbox -Identity $UPN -PrimarySmtpAddress $UPN -EmailAddressPolicyEnabled $false
- #Close remote sessions
- Get-PSSession -Name $Session| Remove-PSSession
- #END CREATE REMOTE MAILBOX
- ##############################
- #Final Dir-Sync to show all changes - This is a custom built function
- Start-ADConnectDeltaSync
- Write-Output "An Active Directory account and Mailbox has been created for $Ufirstname $Ulastname."
- #SMTP Server
- $SMTPServer = "mailrelay.domain.local"
- #Email to [email protected] with all user info
- # Email Subject Set Here
- $subject = "New Account for $Ufirstname $Ulastname"
- # Email Body Set Here, Note You can use HTML, including Images.
- $body = "<font face=Arial>
- Hello,
- <p>relevant info regarding user account goes here </br>
- </font>
- </p>"
- # Send Email Message
- Send-Mailmessage -smtpServer $smtpServer -from $from -to $Recipient -subject $subject -body $body -bodyasHTML -priority High
- # Email to new user with basic instructions
- # Email Subject Set Here
- $NEsubject = 'Welcome!'
- # Email Body Set Here, Note You can use HTML, including Images.
- $NEbody ="<font face=Arial size=Small>
- Hi,
- <p>Welcome aboard info for your freshly minted user.
- </font>
- </p>"
- #While Loop for eamil to activate
- $me = Get-Mailbox -Identity $UPN -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
- while($me.IsMailboxEnabled -eq $null){
- Write-Output "Email not active yet"
- Start-sleep -Seconds 10
- #re-run variable until mailbox becomes available
- $me = Get-Mailbox -Identity $UPN -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
- }
- # Send Email Message
- Write-Output "Email active"
- Send-Mailmessage -smtpServer $smtpServer -from $NEFrom -to $UPN -subject $NEsubject -body $NEbody -bodyasHTML -priority High
- } # End if $EmailRquired switch exists
- else
- {# If $EmailRequired Switch does not exist
- Write-Output "An Active Directory account for $Ufirstname $Ulastname has been created."
- #Email to [email protected] with all user info
- $SMTPServer = "mailrelay.domain.local"
- # Email Subject Set Here
- $subject = "New Account for $Ufirstname $Ulastname"
- # Email Body Set Here, Note You can use HTML, including Images.
- $body = "<font face=Arial>
- Hello,
- <p>relevant info regarding user account goes here </br>
- </p>"
- # Send Email Message
- Send-Mailmessage -smtpServer $smtpServer -from $from -to $Recipient -subject $subject -body $body -bodyasHTML -priority High
- }#End if $EmailRequired Switch does not exist
- }# End New-Employee
Add Comment
Please, Sign In to add comment