ShiftNick

New User Account from Word Document

Aug 11th, 2016
703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function New-Employee{
  2. <#
  3. .SYNOPSIS
  4. 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.
  5.  
  6. .DESCRIPTION
  7. Pulls data from New Hire word doc and creates useraccount and mailbox
  8.  
  9. .PARAMETER FilePath
  10. Path to the new hire document for the user in question.  Double quotes are required around the file path.
  11.  
  12. .PARAMETER EmailRequired
  13. Denote whether the user requires an email address or not
  14.  
  15. .PARAMETER UsageLocation
  16. Sets the license usage location for the user in Office365 CA (Canada), US (USA
  17.  
  18. .PARAMETER LicenseType
  19. Sets license type to Enterprise or Standard
  20.  
  21. .PARAMETER NoUserFolder
  22. Switch that indicates no user folder is required.  Default action is to create a folder if this switch is not present
  23.  
  24. .INPUTS
  25.  
  26. .OUTPUTS
  27.  
  28. .NOTES
  29. New-EmployeeV1 Created by Nick Smyth with the Windows Powershell ISE
  30. Update Version 1.7.1 - September 25, 2015 - Added User folder creation, Set-Acl's on folder and home drive mapping.
  31. 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
  32. Added sleep of 10 seconds after folder creation.
  33. Update Version 1.7.3 - November 30, 2015 - Added -EmailAddressPolicyEnabled $false to line 296 "#Set Primary SMTP Address"
  34. Update Version 1.7.4 - December 21, 2015 - Check for exact match on UPN - Add switch to decline creating user folder
  35. Update Version 1.8 - May 27, 2016 - Added automated sending of welcome email to new users with email addresses
  36. .EXAMPLE
  37. New-Employee -FilePath "c:\temp\Newhire.docx"
  38.  
  39. .EXAMPLE
  40. New-Employee -FilePath "c:\temp\Newhire.docx" -EmailRequired -UsageLocation CA -LicenseType Enterprise
  41.  
  42. .EXAMPLE
  43. New-Employee -FilePath "c:\temp\Newhire.docx" -NoUserFolder
  44.  
  45. .EXAMPLE
  46. New-Employee -FilePath "c:\temp\Newhire.docx" -NoUserFolder -EmailRequired -UsageLocation CA -LicenseType Enterprise
  47. #>
  48.  
  49.     [CmdletBinding()]
  50.      Param (
  51.         [Parameter(ParameterSetName = "Default",Mandatory,valueFromPipeline,Position=0)]
  52.         [Parameter(ParameterSetName = "EmailRequired",Mandatory,valueFromPipeline,Position=0)]
  53.         [String[]]$FilePath,
  54.        
  55.         [Parameter(ParameterSetName = "EmailRequired",Mandatory)]
  56.         [Switch]$EmailRequired,
  57.        
  58.         [Parameter(ParameterSetName = "EmailRequired",Mandatory)]
  59.         [ValidateSet("CA","US")]
  60.         [string]$UsageLocation,
  61.        
  62.         [Parameter(ParameterSetName = "EmailRequired",Mandatory)]
  63.         [ValidateSet("Standard","Enterprise")]
  64.         [string]$LicenseType,
  65.  
  66.         [Parameter(ParameterSetName = "Default",valueFromPipeline,Position=0)]
  67.         [Parameter(ParameterSetName = "EmailRequired",valueFromPipeline,Position=0)]
  68.         [Switch]$NoUserFolder
  69.  
  70.  
  71.     )
  72.  
  73. $DocPath = "$FilePath"
  74.  
  75. Write-output 'Parsing Word document and editing data, please wait...'
  76.  
  77. #Open Word document
  78. $SearchArray = @('1. First Name:','2. Last Name:','3. Job Title:','4. Manager/Supervisor','User Name:')
  79. $Word = New-Object -ComObject Word.Application
  80. $Document = $Word.Documents.Open($DocPath)
  81. $CSVInfo = $Document.Paragraphs | ForEach-Object {
  82.     foreach ($SearchText in $SearchArray) {
  83.         $_.Range.Text | Where-Object {$_ -match $SearchText} | ForEach-Object {
  84.             $_ -split ':' | Select-Object -Last 1
  85.         }
  86.     }
  87. }
  88. $word.quit()
  89.  
  90.  
  91. ##############################
  92.  
  93. #All contents taken from Word Doc with spaces removed
  94. $Trim = $CSVInfo.trim()
  95. #New user information
  96. $Ufirstname = $Trim | select-object -Index 0
  97. if ($Ufirstname -like "*-*"){
  98.     $UsamFirstname = $Ufirstname.Replace("-","")
  99.     }
  100.     else{
  101.         $UsamFirstname = $Ufirstname
  102.         }
  103.  
  104. $Ulastname = $Trim | select-object -Index 1
  105. if (($Ulastname -like "*’*")){
  106.     $UsamLastname = $Ulastname.Replace("’","")
  107.     }
  108.     else{
  109.         $UsamLastname = $Ulastname
  110.         }
  111.  
  112. if ($Ulastname -like "*-*"){
  113.     $UsamLastname = $Ulastname.Replace("-","")
  114.     }
  115.     else{
  116.         $UsamLastname = $Ulastname
  117.         }
  118. if ($Ulastname -like "* *"){
  119.     $UsamLastname = $Ulastname.Replace(" ","")
  120.     }
  121.     else{
  122.         $UsamLastname = $Ulastname
  123.         }
  124.    
  125. $UDetailedName= $Ulastname + ", " + $Ufirstname
  126. $UPN = $UsamFirstname + "." + $UsamLastname + "@domain.com"
  127. $Password = "123123!"
  128. #SAMAccountName Creation
  129. $i = 1
  130. Do { $Usam = ($Ufirstname.Substring(0,$i++).ToLower() + $Usamlastname.ToLower())
  131.     Try   {$exists = Get-ADUser -LDAPFilter "(sAMAccountName=$Usam)"}
  132.       Catch { }
  133.     }
  134.  Until ($exists -eq $null)
  135.  
  136. #Job Title
  137. $jtitle = $Trim | Select-Object -index 2
  138.  
  139. #Test for exact match on user
  140. $testsam = $UsamFirstname.Substring(0,1) + $UsamLastname
  141. $exactmatch = Get-ADUser -filter {samaccountname -eq $testsam}
  142.  
  143. ##############################
  144.  
  145. #Manger Name
  146. $mname = ($trim | Select-Object -Index 3).split(" ")
  147. $Mfirstname = $mname | select-object -Index 0
  148. $Mlastname = $mname | select-object -Index 1
  149. if($Mlastname -like "*’*"){
  150.     $Mlastname = $Mlastname.Replace("’","'")
  151.     }
  152. $Mdisplayname = "$Mlastname" + ", " + "$Mfirstname"
  153. $Msam = Get-ADUser -Filter {Name -eq $Mdisplayname} | Select -ExpandProperty SamAccountName
  154.  
  155. #User to copy group membership from
  156. $cname = ($trim | Select-Object -Index 4).split(" ")
  157. $Cfirstname = $cname | select-object -Index 0
  158. $Clastname = $cname | select-object -Index 1
  159. if($Clastname -like "*’*"){
  160.     $Clastname = $Clastname.Replace("’","'")
  161.     }
  162. $CDisplayName = "$Clastname" + ", " + "$Cfirstname"
  163. $Csam =  Get-ADUser -filter {Name -eq $CDisplayName} | Select -ExpandProperty SamAccountName
  164. $ou = (get-aduser -Identity $Csam -Properties * | Select -ExpandProperty distinguishedname).split(",",3) | Select -Last 1
  165.  
  166.  
  167. ##############################
  168.  
  169. #DATA VERIFICATION
  170.  
  171. if ($EmailRequired)
  172.     {
  173.         #Verify SAMAccountName, UPN, Job Title, Manager and User to copy groups from
  174.         Write-Output "Please verify the following information is correct" `n
  175.        
  176.         #Check for exact match of user
  177.         if($exactmatch -eq $null){
  178.  
  179.             }else
  180.             {
  181.                 Write-Output "There is already user with the username $($exactmatch.samaccountname) with the name $($exactmatch.name),"
  182.                 Write-Output 'Please verify this is not a duplicate user before proceeding'
  183.                 Read-Host 'Press Enter to continue or CTRL + C to exit.' `n
  184.  
  185.                 }
  186.         Write-Output "The username for $Ufirstname $Ulastname is $Usam"
  187.         Write-Output "The UPN for $Ufirstname $Ulastname is $UPN"
  188.         Write-Output "The job title for $Ufirstname $Ulastname is $jtitle"
  189.         Write-Output "The Manager for $Ufirstname $Ulastname is $Msam"
  190.         Write-Output "The user to copy permissions from is $Csam"
  191.        
  192.        
  193.         #Verify Usage Location for Office365 License and License Type
  194.         Write-Output "You have selected $UsageLocation, as the location for this user"
  195.         Write-Output "You have selected $LicenseType, as the license for this user"
  196.         Read-Host "If this information is correct, press Enter to continue or CTRL + C to exit."
  197.        
  198.         }
  199.         Else
  200.             {
  201.             #Verify Job Title, Manager and User to copy groups from
  202.             Write-Output "Please verify the following information is correct" `n
  203.            
  204.             #Check for exact match of user
  205.             if($exactmatch -eq $null){
  206.  
  207.             }else
  208.             {
  209.                 Write-Output "There is already user with the username $($exactmatch.samaccountname) with the name $($exactmatch.name),"
  210.                 Write-Output 'Please verify this is not a duplicate user before proceeding'
  211.                 Read-Host 'Press Enter to continue or CTRL + C to exit.' `n
  212.  
  213.                 }
  214.             Write-Output "The username for $Ufirstname $Ulastname is $Usam"
  215.             Write-Output "The UPN for $Ufirstname $Ulastname is $UPN"
  216.             Write-Output "The job title for $Ufirstname $Ulastname is $jtitle"
  217.             Write-Output "The Manager for $Ufirstname $Ulastname is $Msam"
  218.             Write-Output "The user to copy permissions from is $Csam"
  219.             Read-Host "If this information is correct, press Enter to continue or CTRL + C to exit."
  220.             }
  221.  
  222.  
  223.  
  224. ##############################
  225.  
  226. # ACTIVE DIRECTORY ACCOUNT CREATION
  227.  
  228. #Create New User
  229. 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
  230.  
  231. #Copy Group Memberships
  232. Get-ADUser -Identity $Csam -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $usam
  233.  
  234. ##############################
  235.  
  236. # FOLDER CREATION, SET ACLS AND MAP HOME DRIVE - ADDED SEPT 25, 2015
  237.  
  238.     if($NoUserFolder){
  239.  
  240.         }
  241.         Else{
  242.  
  243.             #user folder path
  244.             $ufolder = "\\fileshare\users\"
  245.  
  246.             Write-Output 'Creating User folder and setting ACLs'
  247.  
  248.             #Create new user folder
  249.             New-Item -Path $ufolder -Name $usam -ItemType Directory
  250.  
  251.             #Wait 15 seconds to before creating ACL
  252.             Start-Sleep -Seconds 10
  253.  
  254.             #Set ACL on new user folder
  255.  
  256.                 #Get current ACL of folder
  257.                 $Acl = Get-Acl "$ufolder$Usam"
  258.  
  259.                 #Create Object with new permission rules
  260.                 $Ar = New-Object  system.security.accesscontrol.filesystemaccessrule($Usam,"DeleteSubdirectoriesAndFiles, Modify, TakeOwnership, Synchronize", "ContainerInherit,ObjectInherit", "None", "Allow")
  261.  
  262.                 #Set the access rule
  263.                 $Acl.SetAccessRule($Ar)
  264.  
  265.                 #Apply to the folder
  266.                 Set-Acl "$ufolder$Usam" $Acl
  267.  
  268.             #Set Home Directory
  269.             Set-Aduser -Identity $Usam -HomeDrive M: -HomeDirectory "$ufolder$Usam"
  270.  
  271.             }
  272.  
  273.  
  274. ##############################
  275.  
  276. # CHECK FOR $EMAILREQUIRED SWITCH
  277.  
  278. if($EmailRequired)
  279.     {# If $EmailRequired switch exists
  280.  
  281.  
  282.         #Login Loop that will verify Office365 credentials before proceeding
  283.         $problem = $true
  284.         while ($problem -eq $true) {
  285.             try {#Open Connection to Office365
  286.                 Import-Module MSOnline
  287.                 #Admin Credential for O365
  288.                 $O365Cred = Get-Credential -message "Please enter your Office365 Admin credentials"
  289.                 #Create Remote session to office 365
  290.                 $O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection -ea Stop
  291.        
  292.                 Write-Output 'Logon Successful. Please wait...'
  293.                 $problem = $false
  294.        
  295.                 #Enter remote session to O365
  296.                 Import-PSSession $O365Session -AllowClobber
  297.                 Connect-MsolService –Credential $O365Cred
  298.        
  299.                 }
  300.  
  301.             catch {
  302.                 Write-Output 'Your username or password was incorrect, please try again'
  303.             }
  304.  
  305.         }#End Login verification loop
  306.        
  307.         ##############################
  308.  
  309.         #Run Manual DirSync - Custom built function
  310.         Start-ADConnectDeltaSync
  311.  
  312.         #Waits to give Dirsync a chance to run before attempting mailbox creation
  313.         Write-Output "Running Dirsync - No action required, creation of mailbox will start automatically"
  314.         Start-Sleep -Seconds 30
  315.  
  316.         ##############################
  317.        
  318.         #ADD LICENSE AND USAGE LOCATION FOR OFFICE 365
  319.        
  320.         #Sets license type variable
  321.         $LIC = "domain:" + "$LicenseType" + "pack";
  322.      
  323.         #Set usage location for license. CA=Canada, US=USA
  324.         Set-MsolUser -UserPrincipalName $UPN -UsageLocation $UsageLocation
  325.                
  326.         #Update variable for the appropriate license type
  327.         Set-MsolUserLicense -UserPrincipalName  $UPN -AddLicenses $LIC
  328.  
  329.         #END ADD LICENSE AND USAGE LOCATION FOR OFFICE 365
  330.  
  331.         ##############################
  332.  
  333.         #CREATE REMOTE MAILBOX
  334.         #Open connection to On Prem Exchange server
  335.         $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchangeonprem/PowerShell/ -Authentication Kerberos -WarningAction:SilentlyContinue
  336.         Import-PSSession $Session -AllowClobber
  337.  
  338.         #Set RemoteRoutingAddress variable
  339.         $RRA = $UsamFirstname + "." + $UsamLastname + "@domain.mail.onmicrosoft.com"
  340.  
  341.         #Enable remote mailbox for user
  342.         Enable-RemoteMailbox -Identity $UPN -RemoteRoutingAddress $RRA | Out-Null
  343.  
  344.         #Set Primary SMTP Address
  345.         Set-RemoteMailbox -Identity $UPN -PrimarySmtpAddress $UPN -EmailAddressPolicyEnabled $false
  346.  
  347.         #Close remote sessions
  348.         Get-PSSession -Name $Session| Remove-PSSession
  349.  
  350.         #END CREATE REMOTE MAILBOX
  351.  
  352.         ##############################
  353.  
  354.         #Final Dir-Sync to show all changes - This is a custom built function
  355.         Start-ADConnectDeltaSync
  356.  
  357.         Write-Output "An Active Directory account and Mailbox has been created for $Ufirstname $Ulastname."
  358.  
  359.         #SMTP Server
  360.         $SMTPServer = "mailrelay.domain.local"
  361.                
  362.         #Email to [email protected] with all user info
  363.  
  364.         $From = "IS Support <[email protected]>"
  365.         $Recipient = "New Hire <[email protected]>"
  366.        
  367.         # Email Subject Set Here
  368.         $subject = "New Account for $Ufirstname $Ulastname"
  369.    
  370.         # Email Body Set Here, Note You can use HTML, including Images.
  371.         $body = "<font face=Arial>
  372.        Hello,
  373.        <p>relevant info regarding user account goes here </br>
  374.        </font>
  375.        </p>"
  376.    
  377.         # Send Email Message
  378.         Send-Mailmessage -smtpServer $smtpServer -from $from -to $Recipient -subject $subject -body $body -bodyasHTML -priority High
  379.  
  380.        
  381.         # Email to new user with basic instructions
  382.         $NEFrom = "Helpdesk <[email protected]>"
  383.  
  384.         # Email Subject Set Here
  385.         $NEsubject = 'Welcome!'
  386.  
  387.         # Email Body Set Here, Note You can use HTML, including Images.
  388.         $NEbody ="<font face=Arial size=Small>
  389.        Hi,
  390.        <p>Welcome aboard info for your freshly minted user.
  391.        </font>
  392.        </p>"  
  393.      
  394.         #While Loop for eamil to activate
  395.         $me = Get-Mailbox -Identity $UPN -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
  396.  
  397.         while($me.IsMailboxEnabled -eq $null){
  398.  
  399.         Write-Output "Email not active yet"
  400.         Start-sleep -Seconds 10
  401.  
  402.         #re-run variable until mailbox becomes available
  403.         $me = Get-Mailbox -Identity $UPN -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
  404.  
  405.         }
  406.         # Send Email Message
  407.         Write-Output "Email active"
  408.         Send-Mailmessage -smtpServer $smtpServer -from $NEFrom -to $UPN -subject $NEsubject -body $NEbody -bodyasHTML -priority High
  409.  
  410.        
  411.  
  412.     } # End if $EmailRquired switch exists
  413.    
  414.     else
  415.         {# If $EmailRequired Switch does not exist
  416.  
  417.         Write-Output "An Active Directory account for $Ufirstname $Ulastname has been created."
  418.        
  419.         #Email to [email protected] with all user info
  420.  
  421.         $SMTPServer = "mailrelay.domain.local"
  422.         $From = "IS Support <[email protected]>"
  423.         $Recipient = "New Hire <[email protected]>"
  424.        
  425.         # Email Subject Set Here
  426.         $subject = "New Account for $Ufirstname $Ulastname"
  427.    
  428.         # Email Body Set Here, Note You can use HTML, including Images.
  429.         $body = "<font face=Arial>
  430.        Hello,
  431.        <p>relevant info regarding user account goes here </br>
  432.        </p>"
  433.    
  434.         # Send Email Message
  435.         Send-Mailmessage -smtpServer $smtpServer -from $from -to $Recipient -subject $subject -body $body -bodyasHTML -priority High
  436.         }#End if $EmailRequired Switch does not exist
  437.  
  438. }# End New-Employee
Add Comment
Please, Sign In to add comment