⬆️ ⬇️

Automate Personnel Changes on PowerShell

image This article focuses on automating the creation, relocation and firing of people in accordance with the personnel changes made in 1C.



The principle of the script is to parse unloaded user data from 1C and assign this data to script variables with further use.



In our company, after the user's entry in 1C, a CSV file is created with the data, an example below:

document typeuserNameFioDepartmentDepartment
recruitmentUSERtester1Ivanov Ivan IvanovichDisponentDivision of disposition and paperwork
movingUSERtester2Petrov Ivan IvanovichRenewal ManagerCredit and Insurance Department
dismissalUSERtester3Sidorov Ivan IvanovichRenewal ManagerCredit and Insurance Department


The script contains three functions (usrcreate; usrmove; usrdelete) in accordance with the types of operations:



Recruitment



We are looking for a user template based on the position and department name, after finding the necessary attributes and groups, we write them to the new user, at the same time a home folder is created and connected, and the mailing address is associated. A report is sent to the mail with the user name, full name and a list of groups to which it was added.

')

Frame moving



We find the user template for the new position and the new department of the employee, from which we get the new list of groups and the OU address, after finding the old groups from the user being moved and adding it to the new ones, simultaneously transfer it to the OU corresponding to the new department (if there is such a division in AD), and change posts for new ones respectively. A report with a new post, department and groups is sent to the post office.



Dismissal



Disable the mailbox, remove the user from all groups, move it to the folder for disabled users and disable its account. A report is sent to the mail that the user is disconnected and dismissed.



The script includes a number of checks:



Check for need to start Exchange and Active Directory snap-ins



In this test, data is searched for processing if they are not found. The snap-ins will not be loaded, which will save approximately 7 seconds of time.



Check for existence of data for processing in variables $ getstaff | $ movestaff | $ delstaff



To run the functions of creating, moving and deleting users.



Check on the existence of the created user



To check for duplicate tasks to create a user.



Check on the existence of the user's network folder



To bypass the folder existence error.



Position and department check



To check for duplication of the transfer request when the user has already been moved to a new position.



Check for user termination



To check for duplication of applications for dismissal, when the user has already been dismissed.



Description of script variables:
$ smtpservMailing (Server)
$ smtpfromMailing (From whom)
$ smtptoMailing (To)
$ opertypeType of user operation
$ usrnameSamAccountName
$ FioFull Name
$ curdateCurrent date in day.month.year format
$ del$ Delstaff array element
$ delstaffUser details for dismissal
$ departmentDepartment
$ dirPlace where 1C unloads CSV
$ getElement of the array $ getstaff
$ getstaffUser data for recruitment
$ groupsList of copied groups for report
$ moveThe element of the array $ movestaff
$ movestaffUser data for personnel movement
$ newusernameName
$ newusersurnameSurname
$ PositionPosition
$ sdelDistributed $ del
$ sgetPublic $ get
$ smoveShared $ move
$ shablonSamAccountName user template
$ spisokfList of files in the download directory from 1C
$ todayfThe file which contains the personnel changes for today
$ usrcopyfromUser template
$ usrexistUser login to check for existence
$ usrpathUser location in AD
$ usrpropTemplate User Properties
$ usrdomainYour domain
$ SessionSession with Exchange Management Console
$ usrshareAddress of the user folder on the network storage
$ passTemporary user password
$ companyCompany name
$ usrstateCompany location
$ usrCityCity
$ usrStreetAddressStreet House Corps
$ curuserpathThe current location of the user being moved to AD
$ newuserpathTarget location of user being moved to AD
$ usrmoveddepCurrent user department to check for duplicate move order
$ usrmovedtitThe current user position to check for duplicate move order


Elements in $ get | $ move | $ del arrays

[0]Type of operation: recruitment / relocation / dismissal
[one]SamAccountName
[2]Full name
[3]Position
[four]Department




The script itself:



#   $smtpserv = "post.domain.local" $smtpfrom = "AUTOUSERCHANGER@domain.local" $smtpto = "sysadmin@domain.local" $encoding = [System.Text.Encoding]::UTF8 $smtpBody = "" #      1 $dir= "\\fileserver\1C\" # $usrdomain="domain.local" #  csv   $spisokf=Get-Childitem -File -Path $dir*.csv | Select-Object -ExpandProperty Name #      $curdate=Get-Date -Format dd.MM.yyyy $todayf=$spisokf | Select-String $curdate #       $getstaff= Get-Content $dir$todayf |Select-String "  " $movestaff= Get-Content $dir$todayf |Select-String "" $delstaff= Get-Content $dir$todayf |Select-String "" #  EXCHANGE  ActiveDirectory if ($getstaff -ne $null -or $movestaff -ne $null -or $delstaff -ne $null) { $Session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://post.domain.local/PowerShell/ -Authentication Kerberos Import-PSSession $Session -AllowClobber | out-null Import-Module ActiveDirectory } else { Write-Host "     " } #  function usrcreate () { #     ForEach ($get in $getstaff) { #  $sget=$get -split (";") $opertype = $sget[0] $usrname=$sget[1] $FIO=$sget[2] $Position=$sget[3] $department=$sget[4] #    $usrexist=Get-ADUser -filter {(SamAccountName -eq $usrname)} | Select-Object -ExpandProperty SamAccountName if ($usrexist -eq $null) { #   $usrshare="\\FILESERVER\Users\$usrname" #    $shablon=Get-ADUser -filter { (physicalDeliveryOfficeName -like $department) -and (title -like $Position) -and (Enabled -eq $true) -and (SamAccountName -ne $usrname)} | Select-Object -ExpandProperty SamAccountName $usrcopyfrom=$shablon[1] #-Path $usrprop= Get-ADUser -Identity $usrcopyfrom | Select-Object -ExpandProperty DistinguishedName $usrpath= ($usrprop -split ',',2)[1] #-name $newusername=($FIO-split ' ')[1] #-Surname $newusersurname=($FIO-split ' ')[0] #-AccountPassword $pass="Qwerty01" #-company $company= Get-ADUser -Identity $usrcopyfrom -Properties Company | Select-Object -ExpandProperty company #-State $usrstate= Get-ADUser -Identity $usrcopyfrom -Properties State | Select-Object -ExpandProperty State #-City $usrCity= Get-ADUser -Identity $usrcopyfrom -Properties City | Select-Object -ExpandProperty City #-StreetAddress $usrStreetAddress= Get-ADUser -Identity $usrcopyfrom -Properties StreetAddress | Select-Object -ExpandProperty StreetAddress #  New-ADUser ` -name $FIO ` -AccountPassword (ConvertTo-SecureString $pass -AsPlainText -Force) ` -ChangePasswordAtLogon $true ` -Company $company ` -Department $department ` -Description $Position ` -DisplayName $FIO ` -Enabled $true ` -HomeDirectory $usrshare ` -HomeDrive "<b>   </b>" ` -Path $usrpath ` -PostalCode "<b>  </b>" ` -SamAccountName $usrname ` -UserPrincipalName "$usrname@$usrdomain" ` -State $usrstate ` -StreetAddress $usrStreetAddress ` -Surname $newusersurname ` -Title $Position ` -GivenName $newusername ` -City $usrCity ` -Office $department ` | out-null #   Start-Sleep -Seconds 10 #     $groups=Get-ADUser -Identity $usrcopyfrom -Properties memberof | Select-Object -ExpandProperty memberof|Add-ADGroupMember -Members $usrname -PassThru | Select-Object -ExpandProperty SamAccountName #      (       ) if(!(Test-Path -Path $usrshare )) { New-item $usrshare -type directory | out-null $acl = Get-Acl $usrshare $acl | Format-List $acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $acl.SetAccessRuleProtection($true, $true) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule ("$usrdomain\$usrname","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.addAccessRule($rule) Set-Acl $usrshare $acl | out-null } else { $acl = Get-Acl $usrshare $acl | Format-List $acl.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $acl.SetAccessRuleProtection($true, $true) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule ("$usrdomain\$usrname","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.addAccessRule($rule) Set-Acl $usrshare $acl | out-null } #   Enable-Mailbox "$usrname@$usrdomain" -Database "<b>   </b>" | out-null #    foreach ($group in $groups) {$smtpBody = $smtpBody +$group+"`n`n"} #    Send-MailMessage -From $smtpfrom -Subject $opertype -To $smtpto -Body " $FIO ($usrname) ""$Position""  ""$department"" .`n`n  :`n$smtpBody" -SmtpServer $smtpserv -Encoding $encoding #  $smtpBody="" } else { #    Send-MailMessage -From $smtpfrom -Subject $opertype -To $smtpto -Body " $FIO ($usrname)  ." -SmtpServer $smtpserv -Encoding $encoding } #     (Get-Content $dir$todayf) | Where-Object {$_ -notmatch $get} | Set-Content -Path $dir$todayf -Force } } #   if ($getstaff -ne $null) { #    #usrcreate #   Start-Sleep -Seconds 10 } else { Write-Host "   " } #  function usrmove () { ForEach ($move in $movestaff) { #  $smove=$move -split (";") $opertype = $smove[0] $usrname=$smove[1] $FIO=$smove[2] $Position=$smove[3] $department=$smove[4] #    $usrmoveddep =Get-ADUser -Identity $usrname -Properties Department |Select-Object -ExpandProperty Department $usrmovedtit =Get-ADUser -Identity $usrname -Properties title |Select-Object -ExpandProperty title if ($usrmoveddep -ne $department -or $usrmovedtit -ne $Position) { #    $shablon=Get-ADUser -filter { (physicalDeliveryOfficeName -like $department) -and (title -like $Position) -and (Enabled -eq $true) } | Select-Object -ExpandProperty SamAccountName $usrcopyfrom=$shablon[1] #     Set-ADUser -Identity $usrname -Department $department -Description $Position -Title $Position -Replace @{physicalDeliveryOfficeName = $department} #    $curuserpath= Get-ADUser -Identity $usrname |Select-Object -ExpandProperty DistinguishedName #    $usrprop= Get-ADUser -Identity $usrcopyfrom | Select-Object -ExpandProperty DistinguishedName $newusrpath= ($usrprop -split ',',2)[1] #  Move-ADObject -Identity $curuserpath -TargetPath $newusrpath #       ,   . $ConfirmPreference = "None" $ErrorActionPreference = "SilentlyContinue" #     ,  domain users Remove-ADPrincipalGroupMembership -Identity $usrname -MemberOf $(Get-ADPrincipalGroupMembership -Identity $usrname | Where-Object {$_.DistinguishedName -ne 'CN=Domain Users,CN=Users,DC=<b>domain</b>,DC=<b>local</b>'}) #     $groups=Get-ADUser -Identity $usrcopyfrom -Properties memberof | Select-Object -ExpandProperty memberof|Add-ADGroupMember -Members $usrname -PassThru | Select-Object -ExpandProperty SamAccountName #    foreach ($group in $groups) {$smtpBody = $smtpBody +$group+"`n`n"} #    Send-MailMessage -From $smtpfrom -Subject $opertype -To $smtpto -Body " $FIO ($usrname) ""$Position""  ""$department"" .`n`n  :`n$smtpBody" -SmtpServer $smtpserv -Encoding $encoding #  $smtpBody="" } else { #    Send-MailMessage -From $smtpfrom -Subject $opertype -To $smtpto -Body " $FIO ($usrname)    ""$Position""  ""$department""" -SmtpServer $smtpserv -Encoding $encoding } #     (Get-Content $dir$todayf) | Where-Object {$_ -notmatch $move} | Set-Content -Path $dir$todayf -Force } } #   if ($movestaff -ne $null) { #    #usrmove #   Start-Sleep -Seconds 10 } else { Write-Host "   " } # function usrdelete () { ForEach ($del in $delstaff) { #  $sdel=$del -split (";") $opertype = $sdel[0] $usrname=$sdel[1] $FIO=$sdel[2] $Position=$sdel[3] $department=$sdel[4] #    $usrdeleted =Get-ADUser -Identity $usrname | Where-Object {$_.Enabled -eq $false} if ($usrdeleted -eq $null) { #       ,   . $ConfirmPreference = "None" $ErrorActionPreference = "SilentlyContinue" #   Disable-Mailbox -Identity "$usrname@$usrdomain" -confirm:$false #     ,  domain users Remove-ADPrincipalGroupMembership -Identity $usrname -MemberOf $(Get-ADPrincipalGroupMembership -Identity $usrname | Where-Object {$_.DistinguishedName -ne 'CN=Domain Users,CN=Users,DC=<b>domain</b>,DC=<b>local</b>'}) #    $curuserpath = Get-ADUser -Identity $usrname |Select-Object -ExpandProperty DistinguishedName #      Move-ADObject -Identity $curuserpath -TargetPath "OU=USER_DISABLE,OU=TO_DELETE_USER_COMPUTER_GROUP_OU,DC=<b>domain</b>,DC=<b>local</b>" #   Disable-ADAccount $usrname #    Send-MailMessage -From $smtpfrom -Subject $opertype -To $smtpto -Body " $FIO ($usrname) ""$Position""  ""$department""   ." -SmtpServer $smtpserv -Encoding $encoding } else { #    Send-MailMessage -From $smtpfrom -Subject $opertype -To $smtpto -Body " $FIO ($usrname) ""$Position""  ""$department""   ." -SmtpServer $smtpserv -Encoding $encoding } #     (Get-Content $dir$todayf) | Where-Object {$_ -notmatch $del} | Set-Content -Path $dir$todayf -Force } } #   if ($delstaff -ne $null) { #    usrdelete #   Start-Sleep -Seconds 10 } else { Write-Host "   " } 

Source: https://habr.com/ru/post/280710/



All Articles