# Автоматическое создание нового пользователя в Active Directory # Создание пользователя с шаблонами прав, а так же отправка пригласительного письма $error.clear() $login=$env:username $spth = split-path -parent $MyInvocation.MyCommand.Definition $ef="$spth\log\error_$login.log" $lg="$spth\log\execute_$login.log" $chars1=[Char[]]"qazwsxedcrfvtgbyhnujmikolp" $chars2=[Char[]]"QAZWSXEDCRFVTGBYHNUJMIKOLP" $chars3=[Char[]]"1234567890" $script:status=0 $co="Domain" $EmailTo = "admin@mail.ru" $EmailCC = "hr@mail.ru" $smtpserver = "smtp.mail.ru" $smtpport = 587 $smtp = new-object Net.Mail.SmtpClient $smtpserver, $smtpport $smtp.Enablessl = $false $smtp.Credentials = New-Object System.Net.NetworkCredential("notice@mail.ru", "password") $smtp.Timeout = 10000 $EmailFrom = "Notice " $text=@("text0","text1","text2","text3","text4") $dirs=@("$spth\log","$spth\body","$spth\html","$spth\archive") Function WriteLog { Param ( [parameter(Mandatory=$true, ValueFromPipeline=$false)] $l ) Process { $d=(get-date -f "yyyy.MM.dd HH:mm:ss") Write-Output "$d $l" | Out-File -append -filepath $lg -encoding "UTF8" } } Foreach ($dr in $dirs) { if (!(Test-Path ($dr))) {md $dr;WriteLog "Missed path: $dr. Folder created"} } Function WriteError { Param ( [parameter(Mandatory=$true, ValueFromPipeline=$false)] $e ) Process { $d=(get-date -f "yyyy.MM.dd HH:mm:ss") Write-Error "$e" if ($error) { Write-Output "$d $error" | Out-file -append -filepath $ef -Encoding "UTF8" $error.clear() } } } Foreach ($t in $text) { if (Test-Path ("$spth\body\$t")) { New-Variable -Name $t -Value (Get-Content $spth\body\$t -encoding "UTF8") } else { WriteError "File $t not found" Exit } } $dblist=Get-ChildItem $spth -Filter {*.csv} if ($dblist) { WriteLog "... System started" ForEach ($db in $dblist) { WriteLog "Progress DB: $db" $tdb=Get-Content $db -encoding "UTF8" if ($tdb -like "*;*") { WriteLog "Convert DB: $db" $tdb=$tdb -Replace (';','","') ForEach ($b in $tdb) {$rdb+=@('"'+$b+'"')} Write-Output $rdb | Out-file -filepath $db -Encoding "UTF8" } else { WriteError "Convert DB skipped" } $users=import-csv $db -Encoding UTF8 if ($error) {WriteError "Convert DB fails:";Exit} Foreach ($u in $users) {WriteLog "Imported user: $u"} if(Test-Path ("$spth\log\addb_$login.csv")) {$addb = import-csv $spth\log\addb_$login.csv -Encoding UTF8} else {$addb = @()} ForEach ($user in $users) { WriteLog "Progress user: $user" $nuser=$null if ($user.password) { $script:pwd = $user.password WriteLog "Password is set. Value = $pwd" } else { $p1 = ($chars1 | Get-Random -Count 3) -join "" $p2 = ($chars2 | Get-Random -Count 3) -join "" $p3 = ($chars3 | Get-Random -Count 3) -join "" $script:pwd = $p1+$p2+$p3 WriteLog "Password is not set. New value generated = $pwd" } $msg = New-Object system.net.mail.mailmessage $msg.To.Add($EmailTo) $msg.IsBodyHTML = $True $msg.CC.Add($EmailCC) $msg.BodyEncoding = [System.Text.Encoding]::UTF8 $msg.From = $EmailFrom $ufname=$user.firstname if (!($ufname)) {WriteError "User Firstname not set";Exit} $ulname=$user.lastname if (!($ulname)) {WriteError "User Lastname not set";Exit} $utype=$user.type $usmgr=$user.manager $usdep=$user.department $uspos=$user.title $uscity=$user.city $mldomain="@"+$user.emldomain $un="$ulname $ufname" $groups=$user.groups -split "," $bdgr=$user.groups $Body2 = "Password: $pwd


Last Name: $ulname
First Name: $ufname

Group membership:
$bdgr
" if ($user.acc) {$acc=$user.acc} else { $acc=$user.lastname $acc=$acc.tolower() } if ($utype) { if ($utype -match "alfa") { $acc="alfa_"+$acc WriteLog "User type is set to alfa. Username set to $acc" } elseif ($utype -match "bravo") { $acc="bravo_"+$acc WriteLog "User type is set to bravo. Username set to $acc" } else { WriteLog "User type is not set. Used default values" } } $fatt="$spth\html\$acc.html" Function CreateUser { Param ( [parameter(Mandatory=$true, ValueFromPipeline=$false)] $newacc ) Begin { $ou="OU=Users,OU=Moscow,OU=Russia,OU=Offices,DC=domain,DC=local" $welcome=$null $script:email=$newacc+$mldomain $upn=$newacc+"@domail.local" $nuser=Get-ADUser -Filter {sAMAccountName -eq $newacc} $fatt="$spth\html\$newacc.html" if ($error) {WriteError "Get-ADUser fails:";Break} } Process { if ($addb.acc -notcontains $newacc) { if ($nuser -eq $null) { $welcome = $text0+$ufname+$text1+$email+$text2+$newacc+$text3+$pwd+$text4 Write-Output $welcome | Out-File -filepath $fatt -encoding "UTF8" New-ADUser -SamAccountName $newacc -Name $un -DisplayName $un -GivenName $ufname -Surname $ulname -Company $co -Organization $co -UserPrincipalName $upn -Country "RU" -Manager $usmgr -Department $usdep -Title $uspos -City $uscity -OtherAttributes @{'mail'=$email;} -PasswordNeverExpires $true -CannotChangePassword $false -AccountPassword (ConvertTo-SecureString $pwd -AsPlainText -Force) -Path $ou -Enabled $true if ($error) {WriteError "New-ADUser fails:";Break} ForEach ($grp in $groups) { Add-ADGroupMember $grp $newacc if ($error) {WriteError "Add-ADGroupMember fails:";Break} } $Body0 = "New user: $newacc
" $Body1 = "EMail: $email
OU: $ou
" $Body=$Body0+$Body1+$Body2 $Subject = "New user created ($newacc)" $msg.Subject = $Subject $att = new-object Net.Mail.Attachment($fatt) $msg.Attachments.Add($att) $msg.body = $Body $html = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString($Body, $null, "text/html") $msg.AlternateViews.Add($html) $smtp.Send($msg) if ($error) {WriteError "Send message fails:"} WriteLog "Email sent (user: $newacc; email: $email)" $script:addb+=New-Object PsObject -Property @{type=$utype;acc=$newacc;firstname=$ufname;lastname=$ulname;groups=$user.groups;password=$pwd;domain=$mldomain;title=$uspos;department=$usdep;manager=$usmgr;city=$uscity} if ($error) {WriteError "Modify addb_$login.csv fails:"} $script:status=1 } } else { $script:status=2 } if ($error) {WriteError "CreateUser fails:"} } } if ($status -eq 0) {CreateUser $acc} if ($status -eq 0) {$acc=$acc+"."+$ufname.tolower()[0];CreateUser $acc} if ($status -eq 0) {$acc=$acc+"."+$ufname.tolower()[1];CreateUser $acc} if ($status -eq 0) {WriteError "Possible user '$acc' exists"} if ($status -eq 2) {WriteError "User '$acc' created earlier";$script:status=0} if ($status -eq 1) {WriteLog "New Account created: $acc";$script:status=0} } $addb | export-csv $spth\log\addb_$login.csv -NoTypeInformation -Encoding UTF8 $d=(get-date -f "yyMMddHHmmss") $n=$d+"-"+$db.Name mv $db "$spth\archive\$n" WriteLog "DB $db archived" } } else { WriteError "New users list not found" } if ($error) {WriteError "Completed with errors:"}