Meet the third PowerShell (part I)

    The pace of development of modern technologies is such that we can barely keep up with them. But today we will run a little ahead, we will learn about the innovations of PowerShell v3, and we will examine them not only with our eyes, but also with our hands.

    Stand

    I built two machines based on Windows Server 2012 RC under Hyper-V, created a forest from one domain called litware.inc. Two machines in the domain are called, respectively, w2012dc1.litware.incand w2012cl1.litware.inc. On w2012dc1revolve Domain Services and DNS, but in w2012cl1not spinning anything but, in fact, most OSes. Also in the domain there is a user user1, a member of the group domain users. Of course, it was possible to install Windows 8 RC on the second machine, so to speak, for beauty, but I decided to save a little disk space by taking one parent virtual hard drive and hooking two children to it instead of using two independent virtual hard drives.
    Also, I must mention that not all the terms that I use are already localized and are on the Microsoft language portal, therefore, I give their translation exactly as I understand these terms, and in parentheses I give the original name in English.

    New opportunities

    First, let's just list them, this:

    • Workflows (Eng. Workflows ) - these are some processes launched sequentially or in parallel, performing complex management tasks. Actually, PowerShell v3 now includes support for the Windows Workflow Foundation, and PowerShell workflows themselves are repeatable, parallelized, interrupted, and restored.
    • Reliable sessions ( Robust sessions ) are PowerShell sessions that are automatically restored after network troubles and similar interruptions. This technology also allows you to disconnect from a session on one machine and connect to the same session on another.
    • Scheduled tasks (Engl. Scheduled jobs ) - jobs PowerShell, which can be performed with certain intervals, or in response to some event.
    • Special session configuration (Eng. Custom session configurations ) - For each PowerShell session, you can predefine a specific set of parameters and save them in a special configuration file, so that you can then enter the session at the ready.
    • Simplified language syntax (Eng. Simplified language syntax ) - is said to have simplified syntax allows PowerShell script to look less like a program, and more similar to natural human language.
    • Search cmdlets (Eng. The Cmdlet discovery ) - automatic loading of the module in which the cmdlet, if the module is, of course, installed on the machine.
    • Show-Command is just one of the new cmdlets that we’ll probably start with.

    Show command

    After its launch, without parameters, a window appears from which it blows with grandeur and chic:
    If you had to look for a particular cmdlet on TechNet before, or even use .NET objects, then here you are, all the modules, all the cmdlets, look for - I do not want.



    Well, if you please, the cmdlets for managing the DNS server and the DNS client service, and if you select a module, for example, a network module, you can find out the cmdlets for configuring the routing table or, for example, the TCP / IP parameters of network interfaces.



    Also I tried to search for the words “share”, “user”, “acl”, “policy”, “adapter”, and so on and so forth, try it, it's interesting.

    Cmdlet discovery

    Associated with the previous one, but not directly dependent. In PowerShell v2 in Windows Server 2008 R2, in order to perform certain operations, you need to connect one or another module, PowerShell v3 automatically determines which module is responsible for running the cmdlet and in the background this module loads without any questions.
    Compare. I decided to get a list of domain group policies if I try to download them in PowerShell v2:

    Get-GPO -All | ft Id #Пусть нас просто столбец с Id интересует, без изысков

    Then we get an error because the GroupPolicy module is not loaded:

    Import-Module GroupPolicy

    Now, if you repeat, then everything goes fine:



    In PowerShell v3, everything is fine from the beginning:



    Simplified language syntax

    Here, it seemed to me, the developers decided to bring the language closer to SQL, well, at least there is a certain analogy. The thing is, they introduced new syntaxes for Foreach-Objectand and Where-Object. Although practical value Foreach:

    Get-Service | Foreach Name

    instead

    Get-Service | Foreach {$_.Name}

    in my opinion, doubtful.
    Another thing Where:

    Get-Service | Where Status -eq Running

    instead

    Get-Service | Where {$_.Status -eq "Running"}

    already nothing, without any braces curly with dollar quotes.
    A couple of new operators also appeared: -Inand -NotIn, indicating a range. With them, I think, everything is more than clear:



    Custom session configurations

    The most remarkable innovation that I want to talk about in the first part is the configuration of the session in conjunction with the delegation of administrative authority. The configuration file itself is a file with the extension .pssc, which just contains a hash table of properties and values: authorship, language, variables, function definitions, etc. The session configuration itself has other properties:

    Get-PSSessionConfiguration | Get-Member

    A picture similar to this one will appear:



    See how many custom settings you have? You can even compare with the picture that appears when you run this command in PowerShell v2 and feel the difference.
    But how to use it? And now I’ll show, I must admit, I have been picking it long enough to write these few lines. So, we sequentially execute:

    $defSSDL = (Get-Item WSMan:\localhost\Service\RootSDDL).Value #Берем SSDL "по умолчанию"
    $SecDescriptor = New-Object -TypeName Security.AccessControl.CommonSecurityDescriptor $false, $false, $defSSDL #Создаем дескриптор безопасности
    $user = Get-ADUser "user1" #Находим в Active Directory нужного пользователя, но лучше, конечно, полномочия давать группам
    $SecDescriptor.DiscretionaryAcl.AddAccess([System.Security.AccessControl.AccessControlType]::Allow, $user.SID.Value, 268435456, [System.Security.AccessControl.InheritanceFlags]::None, [System.Security.AccessControl.PropagationFlags]::None) #Добавляем SID нашего пользователя
    $sddl = $SecDescriptor.GetSddlForm("All") #Забираем то, что получилось
    $creds = Get-Credential "administrator@litware.inc" #Вводим учетные сведения администратора
    New-PSSessionConfigurationFile -Path .\DnsRead.pssc -SessionType RestrictedRemoteServer -VisibleCmdlets "Show-DnsServer*" -ModulesToImport DnsServer #Создаем конфигурационный файл
    Register-PSSessionConfiguration -Name DnsRead -Path .\DnsRead.pssc -AccessMode Remote -SecurityDescriptorSddl $sddl -RunAsCredential $creds #Регистрируем конфигурацию


    Note that I limited the configuration to only a module DnsServerand only to cmdlets starting with Show-DnsServer, this ensures that although the shell itself will be run with user privileges administrator@litware.inc, a remote user user1from a remote machine w2012cl1can do nothing but this:



    Convenient thing, right? By restricting the modules and cmdlets inside PowerShell, we can easily and unconstrained, within our team, administrators of some employees responsible for the DNS, others for the network, and for example, give users the right to snapshot their Hyper-V machines inside VDI, and no one will know the credentials of the user from under which the task is performed! And the finished configuration file is simply transferred from one place to all other servers with similar functions.
    In the next part we will go further, or rather up the list, we will analyze reliable sessions, scheduled tasks and, of course, work processes. Well, and maybe a little touch on the new PowerShell ISE, there is also something to see.

    Also popular now: