Advertisement
hollerith

Import AD users from CSV

Jul 30th, 2018
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ##Beginning of functions
  2.  
  3. Function Format-Email {
  4.  
  5. Param ([string]$WCEmailContent,[string]$UserPrincipalName,[string]$UserPassword)
  6.  
  7. return $WCEmailContent + "User Name = $UserPrincipalName
  8. Password = $UserPassword
  9. Thank You
  10. IT Department"
  11. }
  12.  
  13. Function Send-Email {
  14.  
  15. Param ($Email, $Credential,[string]$WCEmailContent)
  16.  
  17. $From = "karim.buzdar@gmail.com"
  18. $subject = "Domain Account Details"
  19. $Body = $WCEmailContent
  20. $SMTPServer = "smtp.gmail.com"
  21. $SMTPPort = "587"
  22.  
  23. Send-MailMessage -from $From -to $Email -Subject $subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -Credential $Credential -UseSsl
  24.  
  25. }
  26.  
  27. ###End of Functions
  28.  
  29. ##### Beginning of main programme
  30.  
  31. $Credential = (get-Credential) #Getting email credentials to be used for From field in Email message
  32. $UsersFilePath = "C:\Users\Administrator.YOURDOMAIN\Desktop\WC\users.csv" # Files of users information (First name, Last name, Sam account name, Email address)
  33. $WCEmailFile = "C:\Users\Administrator.YOURDOMAIN\Desktop\WC\WCEmail.docx" # File containing welcome email message
  34.  
  35. import-csv -path $UsersFilePath | foreach {
  36.  
  37. $Name = ($_.GivenName + " " + $_.LastName)
  38. $UserPrincipalName = ($_.SamAccountName +@yourdomain.com”)
  39. $UserPassword = Get-Random -maximum 20000 -Minimum 100
  40. $UserPassword = "@" + "user" + $UserPassword.ToString()
  41. #Create user in Students OU
  42.  
  43. new-aduser -name $Name -enabled $true -GivenName $_.GivenName –surname $_.lastName -accountpassword (convertto-securestring $UserPassword -asplaintext -force) -changepasswordatlogon $true -samaccountname $_.SamAccountName –userprincipalname $UserPrincipalName -EmailAddress $_.EmailAddress -Path 'OU=Students,DC=yourdomain,DC=com' -ErrorAction Stop
  44.  
  45. $WCEmailContent = Format-Email -WCEmailContent (Get-Content $WCEmailFile) -UserPrinciPalName $UserPrincipalName -UserPassword $UserPassword
  46.  
  47. Send-Email -Email $_.EmailAddress -Credential $Credential -WCEmailContent $WCEmailContent
  48.  
  49. Write-Host "User Created: $Name"
  50. }
  51.  
  52. ### End of main program
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement