📜 ⬆️ ⬇️

How to stop being a demiurge and entrust the creation of PowerShell entities


When a new employee goes to work, it's usually not enough just to create an account in Active Directory for him: you need to include him in security groups, create a personal folder on a network drive, mailbox, add an account to the ERP \ CRM system ... All this is partially solved by copying the account, but then you need to remember in time and properly configure the attributes of Active Directory .


But there are more elegant solutions to the problem. So, if you are tired of creating accounts manually, I invite you under cat.


Templates and PowerShell


As a simple automation to give the new account the necessary "forms" can be a script in any familiar language. As parameters, it will accept user and department data.


I will look at more interesting examples, essentially based on this method.


Such a script can be a “backend”, to which a previously prepared “frontend” file is transferred in any text format: JSON, XML or CSV.


For example, you can prepare a JSON file to create a user and a folder for him of this type:


{ "ActiveDirectory": { "UserAccounts": [ { "FirstName" : "", "LastName" : "", "Department": "", "UserName": "Iivanov" } ] }, "UserHomeFolders" : [ { "Name": "" } ] } 

In this example, the file has a certain structure and supports the automatic creation of several users at once. Now you need to write a script that will parse the contents of the file and perform certain actions. In our example, the following cmdlet will do:


 [CmdletBinding()] param( [Parameter()] [ValidateNotNullOrEmpty()] [string]$TemplateFilePath = 'C:\temp\users.json' ) $users = Get-Content -Path $TemplateFilePath -Raw | ConvertFrom-Json $users.ActiveDirectory.UserAccounts | ForEach-Object { if ($adUser = Get-AdUser -Filter "samAccountName -eq '$($_.UserName)'") { $setParams = @{ Identity = $_.UserName } if ($adUser.GivenName -ne $_.FirstName) { $setParams.GivenName = $_.FirstName } if ($adUser.SurName -ne $_.LastName) { $setParams.SurName = $_.LastName } if (@($setParams.Keys).Count -gt 1) { $setParams Write-Verbose -Message "   [$($_.UserName)] " Set-AdUser @setParams } else { Write-Verbose -Message " [$($_.UserName)]  " } } else { Write-Verbose -Message "   [$($_.UserName)]..." New-AdUser -Name $_.UserName -GivenName $_.FirstName -SurName $_.LastName -Path "ou=$($_.Department),dc=domain,dc=com" } } $fileServerShare = 'C:\HomeFolders' $users.UserHomeFolders | ForEach-Object { $folderPath = Join-Path -Path $fileServerShare -ChildPath $_.Name if (-not (Test-Path -Path $folderPath -PathType Container)) { Write-Verbose -Message "  [$($folderPath)]..." $null = New-Item -Path $folderPath -Type Directory } else { Write-Verbose -Message " [$($folderPath)]  " } } 

Now you can run the resulting script and enjoy its work:



Cmdlet operation.


It is worth noting that the cmdlet is an example, creates disconnected users and does not include them in any security group. Yes, and the rights to the folder should be set. I propose to modify the solution for your infrastructure independently.

If the cmdlet can be configured to run on a schedule every 5 minutes, then it remains to think of what JSON will form. It can be a simple web interface, a GUI on the same PowerShell and other 1C. An interesting example of using Google Forms as a front and at the same time creating a box for users in the G Suite is described in the material “ Another example of automation or PowerShell + Google Apps Script ”.


I'll look at some more examples of automation that make life easier.


Set permissions on folders


It also happened that according to the regulations for each new user a folder was created on a network drive in a subfolder of the department. And every time there were requests for mail that there was no folder or no access to it - the loaded engineers simply forgot about such trifles.


To reduce the negative, even before the advent of PowerShell, a vbs script was developed. Once a day he connected to AD and collected freshly created users from there. And then I created a folder according to the standard and set the necessary rights using xcacls.vbs with the following command:


 WshShell.Run "cscript.exe C:\xcacls.vbs " + """" + folder + """" +" "+ "/I COPY /R users /G domain\"+ user+ ":F" 

Where user is the name of the new user, folder is the path to the newly created folder, and domain is our domain.


Later, a complex mechanism on AutoIT with a GUI was already developed to create users. He formed the account name according to the rules of transliteration, created users in 1C, and even issued a proximity card for access to the office. The rights to folders in this mechanism are set using the Permissions.au3 library, which uses the system dll advapi32.dll and kernel32.dll .


Part of the script for the required permissions:


 FileWriteLine($logfile, "  "&$path) local $aPermissions[2][3] $aPermissions[0][0]="domain\"& $username $aPermissions[0][1]=1 $aPermissions[0][2]=$GENERIC_ALL $aPermissions[1][0]="Users" $aPermissions[1][1]=1 $aPermissions[1][2]="" _EditObjectPermissions($path, $aPermissions,$SE_FILE_OBJECT,"",1) FileWriteLine($logfile, " ") _ClosePermissionResources() 

In PowerShell, a similar issue of rights will look like this:


 $acl = Get-Acl $path $acl.SetAccessRuleProtection($true,$true) $acl.Access |where {$_.IdentityReference -eq "Domain\Users"} | %{$acl.RemoveAccessRule($_)} $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($username,"FullControl","ContainerInherit,ObjectInherit","None","Allow") $acl | Set-Acl $path 

Perhaps the ACL control is the little thing that is implemented on PowerShell nontrivially. Let us turn to what PowerShell is strong and simple.


Add mail and phone


If you have Exchange installed as a mail server, then the New-Mailbox cmdlet will help you create users with a mailbox right away . To create a user in the original script, you can use the following command:


 New-Mailbox -UserPrincipalName $_.UserName@example.com -Alias $_.UserName -Database "Mailbox" -Name $_.UserName –OrganizationalUnit CorpUsers -Password $password -FirstName $_.FirstName -LastName $_.LastName -DisplayName "$($_.FirstName) $($_.LastName)" -ResetPasswordOnNextLogon $Right 

It will be the same with MS Lync:


 Enable-CsUser -Identity "$($_.UserName)@domain.ru" -RegistrarPool "lync.domain.ru" -SipAddress "sip:$($_.UserName)@domain.ru" 

If you use other solutions — for example, Postfix for mail and Asterisk for telephony — then you will be able to connect via SSH to * nix servers from Windows systems. The procedure is described in detail in the article “ Cross Pollination: Managing Linux from Under Windows, and Vice versa .” Let me remind you that the commands are launched via the Invoke-Command cmdlet:


 Invoke-Command -Hostname linux-server -ScriptBlock {some linux commands} 

More interesting things with other systems, like 1C.


Creating a user in 1C


About the creation of users in 1C: Accounting with AutoIT, I already wrote in the article “ A set of 1C administrator screwdrivers ”. Let me remind you that it is convenient to access 1C “outside” using the v83.comconnector COM object. Since PowerShell also supports COM objects, I’ll give a part of the script for creating users in a new way:


 $obj=new-object -comobject V83.ComConnector $connect=$obj.Connect("Srvr=""servername"";Ref=""basename"";Usr=""login"";Pwd=""password"";") #   $rights=$connect.Metadata.Roles.find($rght) $newuser= $connect..createuser() $newuser.name = "$($surname) $($name)" $newuser.fullname = "$($surname) $($name) $($fathername)" $newuser.StandardAuthentication = "False" $newuser.OSAuthentication="True" $newuser.OSuser="\\DOMAINNAME\ $($Username)" $newuser.Roles.add($rights) $newuser.write() #    "" $bject=$connect.NewObject(".") $newuserS=$bject.CreateItem() $newuserS.code=$"($surname) $($name)" $newuserS.Description="$($surname) $($name) $($fathername)" $newuserS.write() #    $grp=$connect...($group).() $t=$grp..add() $t. = $newuserS. $grp.write() 

Where $ rght is the IB user rights, and $ group is the desired user group. Both values ​​are taken from the template along with the full name.


Of course, the exact script will depend on your specific 1C configuration - do not forget to consult with the 1C programmer.


Create a user from 1C


If the discipline in your organization is not only in the IT department, then you can get rid of the creation of new users. After all, when hiring an employee, they usually enter the base in the HR department, and they also make an appropriate note when they are fired.


The reason for creating a user account, locking it or moving it will not be simply entering the user into the database, but an order to hire, dismiss or move to another department.

In the case of 1C, you can make regular unloading of new and dismissed employees from the database even in the same JSON format. And then let the machine work. An example of a script that handles unloading in CSV format can be found in the article “ Automation of personnel changes on PowerShell ”.


Another option would be to start the scheduled tasks from 1C right away - the benefit of 1C is also quite feature-rich language.


For example, creating a user in AD would look like this:


Caution code in Russian!
  ( , , , ,  = , , AD = "", SID = "",  = "" )   = ;   = COM("LDAP://" + ); AD = .Create("user", "CN=" + ); AD.sAMAccountName = ; AD.description = ; AD.userPrincipalName =  + "@" + ..();   ()  AD.mail = ; ;    AD.pwdLastSet = 0;  AD.pwdLastSet = -1; ; AD.SetInfo(); AD.SetPassword();   = ;  = (); ;    SID = SID(AD.objectSid); AD = AD.distinguishedName; ;    AD.AccountDisabled = ; AD.SetInfo(); ;  ;  

More information about the mechanism of 1C and AD, as well as examples of ready-made functions can be found in the article “ Working with Active Directory from 1C ” on the Infostart portal.


Are you ready to entrust the creation of users, albeit indirectly, to HR employees?


')

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


All Articles