Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [CmdletBinding()]
- param(
- [ValidateScript({Test-Path $_ -PathType Leaf})]
- [Parameter(Mandatory=$True,Position=1)][string]$CSV
- )
- Import-Module ActiveDirectory
- $start = Get-Date
- $domain = Get-ADDomain
- $addomain = $domain.Forest
- $domaindn = $domain.DistinguishedName
- $logfile = ".\CreateUsers.log"
- $nl = "`r`n"
- $ou = "OU=Users,OU=Exchange,$domaindn"
- $pw = ConvertTo-SecureString -AsPlainText "P@55w0rd" -force
- function writelog([string]$message) {
- $timestamp = Get-Date
- $fc = "White"
- if($message.contains("ERROR")) {$fc ="Red"}
- Add-content $logfile -value "$timestamp : $message"
- Write-Host $message -ForegroundColor $fc
- }
- writelog "Importing users from $csv at $start"
- Write-Host $nl
- $loop = 0
- Import-Csv $csv | ForEach-Object {
- Set-Variable -Name testu -Value $null -Scope 0
- $email = $_.PrimarySmtpAddress
- $emailsplit = $email.Split("@")
- $username = $emailsplit[0].ToLower()
- $domain = $emailsplit[1]
- $flname = $username.Split(".")
- $upn = $username + "@" + $addomain
- If($flname.Count -eq 3) {
- $FName = (Get-Culture).TextInfo.ToTitleCase($flname[0].ToLower())
- $MName = $flname[1].ToUpper()
- $LName = (Get-Culture).TextInfo.ToTitleCase($flname[2].ToLower())
- $DisplayName = "$LName, $FName $MName Contoso"
- }
- ElseIf($flname.Count -eq 2) {
- $FName = (Get-Culture).TextInfo.ToTitleCase($flname[0].ToLower())
- $LName = (Get-Culture).TextInfo.ToTitleCase($flname[1].ToLower())
- $DisplayName = "$LName, $FName Contoso"
- }
- else {
- $FName = (Get-Culture).TextInfo.ToTitleCase($flname[0].ToLower())
- $LName = ""
- $DisplayName = (Get-Culture).TextInfo.ToTitleCase($flname[0].ToLower())
- }
- $testu = Get-ADUser -ldapfilter "(samaccountname=$username)"
- $pre2000 = $username
- if($pre2000.length -gt 20) { $pre2000 = $pre2000.Substring(0,20) }
- if($testu -eq $null) {
- writelog "Creating user $DisplayName ($username)"
- New-ADUser -SamAccountName $pre2000 -name $DisplayName -AccountPassword $pw -Path $ou -GivenName $FName `
- -Surname $LName -DisplayName $DisplayName -EmailAddress $email -UserPrincipalName $upn -Enabled $true -ErrorAction Stop
- }
- else {
- #writelog "User $DisplayName ($username) already exists, skipping."
- }
- $loop += 1
- #if ($loop -eq 5) { break }
- }
- $end = Get-Date
- $elapsed = $end - $start
- Write-Host $nl
- writelog "Finished import of $loop users at $end ($elapsed)"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement