Guest User

PowerShell Create AD User from CSV

a guest
Oct 16th, 2024
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.03 KB | None | 0 0
  1. Import-Module ActiveDirectory
  2.  
  3. ## create user function to call from if/else later.
  4. function Create-User{
  5. ## Create array to store all needed values for user creation
  6. $splat = @{
  7. Name = $firstName + ' ' + $lastName
  8. SamAccountName = $username
  9. UserPrincipalName = $email
  10. GivenName = $firstName
  11. Surname = $lastName
  12. DisplayName = $lastname + ', ' + $firstName
  13. EmailAddress = $email
  14. Title = $jobTitle
  15. Department = $department
  16. Enabled = $true
  17. ChangePasswordAtLogon = $true
  18. HomeDirectory = "SANITIZED"
  19. HomeDrive = $homeDrive
  20. HomePhone = "SANITIZED"
  21. OtherAttributes = @{
  22. 'ExtensionAttribute2' = $personalNumber;
  23. }
  24.  
  25. AccountPassword = (ConvertTo-SecureString $password -AsPlainText -Force)
  26. }
  27.  
  28.  
  29. ## Create user in On Prem Active Directory
  30. New-ADUser @splat -path 'SANITIZED' -verbose
  31. }
  32.  
  33. ## Creates a random password for each user
  34. # Randomize passwords
  35. function Get-RandomPassword {
  36. Param(
  37. [Parameter(mandatory = $true)]
  38. [int]$Length
  39. )
  40. Begin {
  41. if ($Length -lt 4) {
  42. End
  43. }
  44. $Numbers = 1..9
  45. $LettersLower = 'abcdefghijklmnopqrstuvwxyz'.ToCharArray()
  46. $LettersUpper = 'ABCEDEFHIJKLMNOPQRSTUVWXYZ'.ToCharArray()
  47. $Special = '!@#$%^&*()=+[{}]/?<>'.ToCharArray()
  48.  
  49. # For the 4 character types (upper, lower, numerical, and special)
  50. $N_Count = [math]::Round($Length * .2)
  51. $L_Count = [math]::Round($Length * .4)
  52. $U_Count = [math]::Round($Length * .2)
  53. $S_Count = [math]::Round($Length * .2)
  54. }
  55. Process {
  56. $Pswrd = $LettersLower | Get-Random -Count $L_Count
  57. $Pswrd += $Numbers | Get-Random -Count $N_Count
  58. $Pswrd += $LettersUpper | Get-Random -Count $U_Count
  59. $Pswrd += $Special | Get-Random -Count $S_Count
  60.  
  61. # If the password length isn't long enough (due to rounding), add X special characters
  62. # Where X is the difference between the desired length and the current length.
  63. if ($Pswrd.length -lt $Length) {
  64. $Pswrd += $Special | Get-Random -Count ($Length - $Pswrd.length)
  65. }
  66.  
  67. # Lastly, grab the $Pswrd string and randomize the order
  68. $Pswrd = ($Pswrd | Get-Random -Count $Length) -join ""
  69. }
  70. End {
  71. $Pswrd
  72. }
  73. }
  74.  
  75. ## Check to see if csv exist or is empty before continuing forward
  76. if (-not(Test-Path C:\psScripts\Onboarding\createADUsers.csv)) {
  77.  
  78. Write-Host "CSV is empty, stop script"
  79. }
  80. else {
  81. ##import csv values from sharepoint list
  82. $adUsers = Import-Csv C:\psScripts\Onboarding\createADUsers.csv -Delimiter ","
  83.  
  84. foreach($user in $adUsers) {
  85. $firstName = $user.FirstName
  86. $lastName = $user.LastName
  87. $firstInitial = $firstName.ToLower()[0]
  88. $jobTitle = $user.Position
  89. $department = $user.Department
  90. $homeDrive = "SANITIZED"
  91. $securityGroups = $user.SecurityGroups
  92. $password = Get-RandomPassword -Length 10
  93. $username = $firstInitial + $lastName.ToLower()
  94. $email = $username + "@SANITIZED"
  95. $licenses = $user.licenses
  96. $personalNumber = $user.personalNumber
  97. $personalEmail = $user.personalEmail
  98.  
  99. ## Set variable to prevent incrementing from adding onto instead of together, ie: 11 vs 1+1=2
  100. $ogusername = $username
  101. $i = 1
  102. $aduser = Get-ADUser -Filter {SamAccountName -eq $username}
  103.  
  104.  
  105. ## If user account already exists, increment name by 1 until one is found
  106. while ($adUser -ne $null) {
  107. Write-Host "Username is already in use. Incrementing by 1 to find a new one"
  108. $username = $ogusername + $i
  109. $email = $username + "@SANITIZED"
  110. $i++
  111. Write-Host "Trying new username of $username"
  112. $aduser = Get-ADUser -Filter {SamAccountName -eq $username}
  113. }
  114.  
  115.  
  116. if ($personalEmail = '') {
  117. $personalEmail = $email
  118. }
  119.  
  120. create-User
  121. Start-Sleep -Seconds 5
  122.  
  123. ## Split $securityGroupsVariable into usable format for foreach loop
  124. $securityGroups = $securityGroups.split(",")
  125.  
  126. ## create correct identifiers for security groups. Loop through each per user and assign the user to the group
  127. foreach ($group in $securityGroups) {
  128. Switch($group) {
  129. "SANITIZED" {$group = "SANITIZED"}
  130. "SANITIZED" {$group = "SANITIZED"}
  131. "SANITIZED" {$group = "SANITIZED"}
  132. "SANITIZED" {$group = "SANITIZED"}
  133. "SANITIZED" {$group = "SANITIZED"}
  134. "SANITIZED" {$group = "SANITIZED"}
  135. "IT" {$group = "IT"}
  136. "SANITIZED" {$group = "SANITIZED"}
  137. "SANITIZED" {$group = "SANITIZED"}
  138. }
  139.  
  140. Add-ADGroupMember -Identity $group -Members $username
  141. }
  142.  
  143. ## Create correct identifiers for license groups. Loop through each per user and assign the user to the group.
  144. ## Valid Licenses:
  145. ## Outlook Mailbox, assigns license on the Azure side based on group membership
  146. ## Office 365, assigns license on the Azure side based on group membership
  147. ## Adobe Pro, assigns a task to IT. Until Adobe can become federated
  148.  
  149.  
  150. ## Split $licenses variable into usable format for foreach loop
  151. $licenses = $licenses.split(",")
  152.  
  153.  
  154. ## Values on left are string format from Forms. Values on right are AD Sec Group Names
  155. foreach ($license in $licenses) {
  156. switch($license) {
  157. "Outlook Mailbox" {$license = "OutlookOnly"}
  158. 'Office 365' {$license = "Office365"}
  159. 'SANITIZED' {$license = "SANITIZED"}
  160. 'SANITIZED' {$license = "SANITIZED"}
  161. 'Adobe Pro' {$license = "AdobePro"}
  162. 'SANITIZED' {$license = "SANITIZED"}
  163. }
  164.  
  165. Add-ADGroupMember -Identity $license -Members $username
  166. }
  167.  
  168. ## Sets the password so it must be changed at first logon
  169. Set-ADUser $username -ChangePasswordAtLogon $True
  170.  
  171.  
  172. ## Send email to HR informing them that the account was created along with their temporary password.
  173. ## Passwords must be changed after logging in.
  174.  
  175. $mailParam = @{
  176. To = 'SANITIZED@SANITIZED'
  177. From = 'SANITIZED@SANITIZED'
  178. Subject = 'New Active Directory User'
  179. Body = "<h2> A new user was created in AD </br>`
  180. User: $firstName $lastname </br>`
  181. Username is: $username </br>`
  182. Password is: $password </br> </br> `
  183. </br>`
  184. Please have users login to change their password during orientation.
  185. </h2>"
  186. SmtpServer = 'SANITIZED.mail.protection.outlook.com'
  187. Port = 25
  188. }
  189.  
  190. Send-MailMessage @mailParam -BodyAsHtml
  191.  
  192. ## Send email to IT Department informing that an account was created, what security groups were assigned, and what licenses were assigned.
  193. $mailParam2 = @{
  194. To = 'SANITIZED@SANITIZED'
  195. From = 'SANITIZED@SANITIZED'
  196. Subject = 'New Active Directory User'
  197. Body = "<h2> A new user was created in AD </br>`
  198. User: $firstName $lastname </br>`
  199. Username: $username </br>`
  200. Security Groups Assigned: $securityGroups </br>`
  201. Licenses Assigned: $licenses </br>`
  202. </br>`
  203. Please verify that licenses exist for any groups that need them.
  204. </br>`
  205. </h2>"
  206. SmtpServer = 'SANITIZED.mail.protection.outlook.com'
  207. Port = 25
  208. }
  209.  
  210. Send-MailMessage @mailParam2 -BodyAsHtml
  211. }
  212.  
  213. ## Delete the createADUsers.csv file
  214. Remove-Item C:\psScripts\Onboarding\createADUsers.csv -Force
  215. }
  216.  
Advertisement
Add Comment
Please, Sign In to add comment