Automatización del mantenimiento de laboratorios de computación en Powershell

Automatización del mantenimiento de laboratorios de computación en Powershell

Durante varios años he estado brindando soporte en la universidad a 10 estaciones de trabajo que operan con el sistema operativo Microsoft Windows 8.1. Principalmente, el soporte consiste en instalar el software necesario para el proceso educativo y garantizar el funcionamiento general.

En cada estación hay 2 usuarios: Administrador y Estudiante. El Administrador tiene acceso completo, mientras que el Estudiante no puede instalar software. Para no complicarme limpiando al usuario Estudiante, esta cuenta simplemente se elimina por completo y se crea de nuevo. Esto conlleva algunas tareas que deben realizarse en cada estación.

Este año decidí automatizar gran parte de las tareas mediante PowerShell sin Active Directory y recopilando en este post algunas recetas que encontré en la red.

Preparación

Inmediatamente me encontré con que en las estaciones está instalado PS 4 y algunos ejemplos del omnisciente Internet no funcionaban. Por lo tanto, antes de ejecutar los scripts resultantes, es necesario realizar un par de acciones:

  1. Instalar Windows Management Framework 5.1
  2. Instalar la versión más reciente PowerShell

Acciones automatizables

  1. Eliminar/crear cuenta de usuario
  2. Acceso automático del usuario especificado
  3. Ejecutar script en el primer inicio del usuario

Eliminar/crear cuenta de usuario

Comencé con la creación. En este caso, es necesario realizar 2 acciones: crear un usuario (New-LocalUser) y agregarlo al grupo (Add-LocalGroupMember). Para mayor comodidad, combiné estos comandos en una función:

Function New-User {
    

    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Name,
        [PARAMETER(Mandatory=$True)][String]$Password
        )

    $Pwd = convertto-securestring $Password -asplaintext -force
    $GroupSID = "S-1-5-32-545"
    New-LocalUser -User $Name -AccountNeverExpires:$true -FullName $Name -Password $Pwd -PasswordNeverExpires:$true
    Add-LocalGroupMember -SID $GroupSID -Member $Name

    Write-Host "-- Usuario $Name creado con la contraseña $Password" -foregroundcolor Green
}

Agrego al grupo por SID, porque en uno de los artículos vi que el SID del grupo Usuarios es el mismo en todas partes: S-1-5-32-545.

La eliminación se organizó de la siguiente manera: eliminar todas las cuentas que fueron creadas por el Administrador. Para ello, a través del objeto WMI de la clase Win32_UserProfile, identifico a todos los usuarios que actualmente no están activos y no son especiales.

Function Remove-Users {
    
    [CmdletBinding()]

    $UsersProfiles = Get-WMIObject -class Win32_UserProfile -ComputerName $env:COMPUTERNAME | Where {!($_.Loaded) -and !($_.Special)}
    foreach($Usr in $UsersProfiles) {
       	$UsrName = $Usr.LocalPath.Split("")[2]
       	Write-Host "-- Eliminando usuario $UsrName ..." -foregroundcolor Green
       	Remove-LocalUser -Name $UsrName
	Remove-WmiObject -Path $Usr.__PATH
        Write-Host "-- Usuario $UsrName eliminado" -foregroundcolor Green
    }
}

Inicio de sesión automático del usuario especificado

Aquí todo se limitó a modificar el registro HKEY_LOCAL_MACHINE. Estas acciones también se agruparon en una pequeña función:

Function Set-AutoLogon {
    

    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Name,
        [PARAMETER(Mandatory=$True)][String]$Password
        )

    $PathToWinlogon = "HKLM:SoftwareMicrosoftWindows NTCurrentVersionWinlogon"
    New-ItemProperty -Path $PathToWinlogon -Name AutoAdminLogon  -Value 1 -PropertyType "String"
    New-ItemProperty -Path $PathToWinlogon -Name DefaultUserName -Value $Name -PropertyType "String"
    New-ItemProperty -Path $PathToWinlogon -Name DefaultPassword -Value $Password -PropertyType "String"
}

Ejecutar script en el primer inicio del usuario

Resulta que no todo se puede configurar antes del primer inicio de un nuevo usuario (lo cual me sorprendió un poco). Por lo tanto, surgió la necesidad de ejecutar un script que realice algunas acciones después del primer inicio:

  1. Configuración del proxy
  2. Prohibición de la creación de archivos en el escritorio
  3. Configuración del panel de control del usuario

Probé varios métodos, pero el que funcionó para mí fue el siguiente: establecer una tarea. Sin embargo, no pude crear la tarea mediante PS. Así que tomé un camino más largo:

schtasks /create /tn LogonUserSettings /tr "pwsh C:ScriptsSettings.ps1" /sc onlogon /ru $env:USERDOMAIN$UserName /rp $Password /f

Pero eso no fue suficiente: Windows solicitó permiso para iniciar sesión como tarea por lotes (SeBatchLogonRight). La búsqueda de una respuesta a cómo hacerlo llevó a esto. el resultado:

LsaWrapper

$Source = @'
using System;
using System.Collections.Generic;
using System.Text;

namespace MyLsaWrapper
{
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Management;
    using System.Runtime.CompilerServices;
    using System.ComponentModel;

    using LSA_HANDLE = IntPtr;

    [StructLayout(LayoutKind.Sequential)]
    struct LSA_OBJECT_ATTRIBUTES
    {
        internal int Length;
        internal IntPtr RootDirectory;
        internal IntPtr ObjectName;
        internal int Attributes;
        internal IntPtr SecurityDescriptor;
        internal IntPtr SecurityQualityOfService;
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct LSA_UNICODE_STRING
    {
        internal ushort Length;
        internal ushort MaximumLength;
        [MarshalAs(UnmanagedType.LPWStr)]
        internal string Buffer;
    }
    sealed class Win32Sec
    {
        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaOpenPolicy(
        LSA_UNICODE_STRING[] SystemName,
        ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
        int AccessMask,
        out IntPtr PolicyHandle
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaAddAccountRights(
        LSA_HANDLE PolicyHandle,
        IntPtr pSID,
        LSA_UNICODE_STRING[] UserRights,
        int CountOfRights
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern int LsaLookupNames2(
        LSA_HANDLE PolicyHandle,
        uint Flags,
        uint Count,
        LSA_UNICODE_STRING[] Names,
        ref IntPtr ReferencedDomains,
        ref IntPtr Sids
        );

        [DllImport("advapi32")]
        internal static extern int LsaNtStatusToWinError(int NTSTATUS);

        [DllImport("advapi32")]
        internal static extern int LsaClose(IntPtr PolicyHandle);

        [DllImport("advapi32")]
        internal static extern int LsaFreeMemory(IntPtr Buffer);

    }
    /// <summary>
    /// This class is used to grant "Log on as a service", "Log on as a batchjob", "Log on localy" etc.
    /// to a user.
    /// </summary>
    public sealed class LsaWrapper : IDisposable
    {
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_TRUST_INFORMATION
        {
            internal LSA_UNICODE_STRING Name;
            internal IntPtr Sid;
        }
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_TRANSLATED_SID2
        {
            internal SidNameUse Use;
            internal IntPtr Sid;
            internal int DomainIndex;
            uint Flags;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct LSA_REFERENCED_DOMAIN_LIST
        {
            internal uint Entries;
            internal LSA_TRUST_INFORMATION Domains;
        }

        enum SidNameUse : int
        {
            User = 1,
            Group = 2,
            Domain = 3,
            Alias = 4,
            KnownGroup = 5,
            DeletedAccount = 6,
            Invalid = 7,
            Unknown = 8,
            Computer = 9
        }

        enum Access : int
        {
            POLICY_READ = 0x20006,
            POLICY_ALL_ACCESS = 0x00F0FFF,
            POLICY_EXECUTE = 0X20801,
            POLICY_WRITE = 0X207F8
        }
        const uint STATUS_ACCESS_DENIED = 0xc0000022;
        const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
        const uint STATUS_NO_MEMORY = 0xc0000017;

        IntPtr lsaHandle;

        public LsaWrapper()
            : this(null)
        { }
        // // local system if systemName is null
        public LsaWrapper(string systemName)
        {
            LSA_OBJECT_ATTRIBUTES lsaAttr;
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
            lsaHandle = IntPtr.Zero;
            LSA_UNICODE_STRING[] system = null;
            if (systemName != null)
            {
                system = new LSA_UNICODE_STRING[1];
                system[0] = InitLsaString(systemName);
            }

            uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
            (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void AddPrivileges(string account, string privilege)
        {
            IntPtr pSid = GetSIDInformation(account);
            LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
            privileges[0] = InitLsaString(privilege);
            uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void Dispose()
        {
            if (lsaHandle != IntPtr.Zero)
            {
                Win32Sec.LsaClose(lsaHandle);
                lsaHandle = IntPtr.Zero;
            }
            GC.SuppressFinalize(this);
        }
        ~LsaWrapper()
        {
            Dispose();
        }
        // helper functions

        IntPtr GetSIDInformation(string account)
        {
            LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
            LSA_TRANSLATED_SID2 lts;
            IntPtr tsids = IntPtr.Zero;
            IntPtr tdom = IntPtr.Zero;
            names[0] = InitLsaString(account);
            lts.Sid = IntPtr.Zero;
            //Console.WriteLine("String account: {0}", names[0].Length);
            int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids);
            if (ret != 0)
                throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret));
            lts = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(tsids,
            typeof(LSA_TRANSLATED_SID2));
            Win32Sec.LsaFreeMemory(tsids);
            Win32Sec.LsaFreeMemory(tdom);
            return lts.Sid;
        }

        static LSA_UNICODE_STRING InitLsaString(string s)
        {
            // Unicode strings max. 32KB
            if (s.Length > 0x7ffe)
                throw new ArgumentException("String too long");
            LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
            lus.Buffer = s;
            lus.Length = (ushort)(s.Length * sizeof(char));
            lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
            return lus;
        }
    }
    public class LsaWrapperCaller
    {
        public static void AddPrivileges(string account, string privilege)
        {
            using (LsaWrapper lsaWrapper = new LsaWrapper())
            {
                lsaWrapper.AddPrivileges(account, privilege);
            }
        }
    }
}
'@

Add-Type -TypeDefinition $Source
[MyLsaWrapper.LsaWrapperCaller]::AddPrivileges($Identity, "SeBatchLogonRight")

El permiso para iniciar sesión como tarea por lotes permitió avanzar: hacia la escritura de un script que se ejecuta bajo el usuario.

Configuración del proxy

La configuración del proxy resultó ser bastante simple. Una solución funcional se encontró rápidamente:

Function Set-Proxy {
    

    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Server,
        [PARAMETER(Mandatory=$True)][Int]$Port
        )

    If ((Test-NetConnection -ComputerName $Server -Port $Port).TcpTestSucceeded) {
        Set-ItemProperty -Path 'HKCU:SoftwareMicrosoftWindowsCurrentVersionInternet Settings' -name ProxyServer -Value "$($Server):$($Port)"
        Set-ItemProperty -Path 'HKCU:SoftwareMicrosoftWindowsCurrentVersionInternet Settings' -name ProxyEnable -Value 1
    } Else {
        Write-Error -Message "-- Dirección o puerto de servidor proxy inválidos:  $($Server):$($Port)"
    }
}

Prohibición de la creación de archivos en el escritorio

Tuve que lidiar más tiempo con la prohibición de crear archivos en el escritorio que con la red. Establecer permisos en la carpeta no fue tan fácil como en los sistemas *nix. Pero también aquí encontré respuestas que pude adaptar exitosamente:

Función Set-AccessRule {
    
    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][Path]$Folder,
        [PARAMETER(Mandatory=$True)][String]$UserName,
        [PARAMETER(Mandatory=$True)][String]$Rules,
        [PARAMETER(Mandatory=$True)][String]$AccessControlType
        )

    # Leemos la lista actual de ACL del escritorio
    $acl = Get-Acl $Folder
    # Creamos una variable con los permisos necesarios
    $fileSystemRights = [System.Security.AccessControl.FileSystemRights]"$Rules"
    # Creamos una variable especificando el usuario, permisos de acceso y tipo de permiso
    $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($UserName, $fileSystemRights, $AccessControlType)
    # Pasamos la variable a la clase FileSystemAccessRule para crear un objeto
    $acl.SetAccessRule($AccessRule)
    # Aplicamos los permisos a la carpeta
    $acl | Set-Acl $Folder
}

Set-AccessRule -Folder $env:USERPROFILEDesktop  -UserName $env:USERNAME -Rules CreateFiles,AppendData,Delete -AccessControlType Deny

Descripción de FileSystemRights en el sitio oficial el sitio web.

Configuración del panel de control del usuario

No era necesario hacerlo, pero pensé que sería genial proporcionar a los estudiantes un panel configurado con programas de uso frecuente. La respuesta se encontró. aquí.

Aplicación Fijada

function Set-PinnedApplication
{
    <#
    .SYNOPSIS
        Gestión de accesos directos en la barra de tareas
    .DESCRIPTION
        Esta función agrega o quita accesos directos en la barra de tareas del usuario
    .EXAMPLE
        #Set-PinnedApplication -Action UnpinfromTaskbar -FilePath "$env:ProgramFilesInternet Exploreriexplore.exe"
    .EXAMPLE
        #Set-PinnedApplication -Action PintoTaskbar -FilePath "${env:ProgramFiles(x86)}Mozilla Firefoxfirefox.exe"
    .PARAMETER Action
        Parámetro obligatorio, que puede tomar uno de dos valores: UnpinfromTaskbar o PintoTaskbar
    .PARAMETER FilePath
        Nombre de la cuenta del usuario para quien se configuran los permisos de acceso (parámetro obligatorio)
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True)][String]$Action, 
        [Parameter(Mandatory=$True)][String]$FilePath
   	)
    if(-not (test-path $FilePath)) { 
   	throw "El FilePath no existe."  
    }
    function InvokeVerb {
   	param([string]$FilePath,$verb)
	$verb = $verb.Replace("&","")
	$path = split-path $FilePath
	$shell = new-object -com "Shell.Application" 
	$folder = $shell.Namespace($path)   
	$item = $folder.Parsename((split-path $FilePath -leaf))
	$itemVerb = $item.Verbs() | ? {$_.Name.Replace("&","") -eq $verb}
	if($itemVerb -eq $null){
		throw "Verbo $verb no encontrado."			
	} else {
		$itemVerb.DoIt()
	}
   }
    function GetVerb {
	param([int]$verbId)
	try {
		$t = [type]"CosmosKey.Util.MuiHelper"
	} catch {
	    $def = [Text.StringBuilder]""
	    [void]$def.AppendLine('[DllImport("user32.dll")]')
	    [void]$def.AppendLine('public static extern int LoadString(IntPtr h,uint id, System.Text.StringBuilder sb,int maxBuffer);')
	    [void]$def.AppendLine('[DllImport("kernel32.dll")]')
	    [void]$def.AppendLine('public static extern IntPtr LoadLibrary(string s);')
	    Add-Type -MemberDefinition $def.ToString() -name MuiHelper -namespace CosmosKey.Util			
	}
	if($global:CosmosKey_Utils_MuiHelper_Shell32 -eq $null){		
	    $global:CosmosKey_Utils_MuiHelper_Shell32 = [CosmosKey.Util.MuiHelper]::LoadLibrary("shell32.dll")
	}
	$maxVerbLength=255
	$verbBuilder = New-Object Text.StringBuilder "",$maxVerbLength
	[void][CosmosKey.Util.MuiHelper]::LoadString($CosmosKey_Utils_MuiHelper_Shell32,$verbId,$verbBuilder,$maxVerbLength)
	return $verbBuilder.ToString()
    }
    $verbs = @{ 
	"PintoTaskbar"=5386
	"UnpinfromTaskbar"=5387
    }
    if($verbs.$Action -eq $null){
   	Throw "Acción $action no soportada`nAcciones soportadas son:`n`tPintoTaskbar`n`tUnpinfromTaskbar"
    }
    InvokeVerb -FilePath $FilePath -Verb $(GetVerb -VerbId $verbs.$action)
}

Conclusión

Los scripts funcionan, el tiempo de mantenimiento de cada estación se ha reducido, el objetivo se ha alcanzado. Para mí, como usuario de Linux, configurar Windows resultó ser una aventura no tan simple, pero educativa. Seguiré desarrollando el script de configuración. Planeo añadir una verificación para la instalación del software y la ejecución del antivirus.

Scripts finales que están en funcionamiento

Ejecutar como Administrador

Function New-User {
    <#
    .SYNOPSIS
        Создание нового пользователя
    .DESCRIPTION
        Данная функция создает нового пользователя и добавляет его в группу Пользователи
    .EXAMPLE
        #New-User "Student" "Student"
    .PARAMETER Name
        Имя нового пользователя (обязательный параметр)
    .PARAMETER Password
        Пароль (обязательный параметр)
    #>

    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Name,
        [PARAMETER(Mandatory=$True)][String]$Password
        )

    $Pwd = convertto-securestring $Password -asplaintext -force
    $GroupSID = "S-1-5-32-545"
    New-LocalUser -User $Name -AccountNeverExpires:$true -FullName $Name -Password $Pwd -PasswordNeverExpires:$true
    Add-LocalGroupMember -SID $GroupSID -Member $Name

    Write-Host "-- Создан пользователь $Name с паролем $Password" -foregroundcolor Green
}

Function Remove-Users {
    <#
    .SYNOPSIS
        Удаление пользователей
    .DESCRIPTION
        Данная функция удаляет пользователей, которые сейчас не активны и не являются специальными
        Удаляются в том числе рабочий каталог и реестр пользователей
    .EXAMPLE
        #Remove-Users
    #>
    [CmdletBinding()]

    $UsersProfiles = Get-WMIObject -class Win32_UserProfile -ComputerName $env:COMPUTERNAME | Where {!($_.Loaded) -and !($_.Special)}
	foreach($Usr in $UsersProfiles) {
        $UsrName = $Usr.LocalPath.Split("")[2]
        Write-Host "-- Удаление пользователя $UsrName ..." -foregroundcolor Green
        Remove-LocalUser -Name $UsrName
		Remove-WmiObject -Path $Usr.__PATH
        Write-Host "-- Пользователь $UsrName удален" -foregroundcolor Green
	}
}

Function Set-AutoLogon {
    <#
    .SYNOPSIS
        Включение автовхода для пользователя
    .DESCRIPTION
        Данная функция включает автовход для указанного пользователя
    .EXAMPLE
        #Set-AutoLogon  "Student" "Student"
    .PARAMETER Name
        Имя пользователя (обязательный параметр)
    .PARAMETER Password
        Пароль (обязательный параметр)
    #>

    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Name,
        [PARAMETER(Mandatory=$True)][String]$Password
        )

    $PathToWinlogon = "HKLM:SoftwareMicrosoftWindows NTCurrentVersionWinlogon"
    New-ItemProperty -Path $PathToWinlogon -Name AutoAdminLogon  -Value 1 -PropertyType "String"
    New-ItemProperty -Path $PathToWinlogon -Name DefaultUserName -Value $Name -PropertyType "String"
    New-ItemProperty -Path $PathToWinlogon -Name DefaultPassword -Value $Password -PropertyType "String"
}

$Source = @'
using System;
using System.Collections.Generic;
using System.Text;

namespace MyLsaWrapper
{
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Management;
    using System.Runtime.CompilerServices;
    using System.ComponentModel;

    using LSA_HANDLE = IntPtr;

    [StructLayout(LayoutKind.Sequential)]
    struct LSA_OBJECT_ATTRIBUTES
    {
        internal int Length;
        internal IntPtr RootDirectory;
        internal IntPtr ObjectName;
        internal int Attributes;
        internal IntPtr SecurityDescriptor;
        internal IntPtr SecurityQualityOfService;
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct LSA_UNICODE_STRING
    {
        internal ushort Length;
        internal ushort MaximumLength;
        [MarshalAs(UnmanagedType.LPWStr)]
        internal string Buffer;
    }
    sealed class Win32Sec
    {
        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaOpenPolicy(
        LSA_UNICODE_STRING[] SystemName,
        ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
        int AccessMask,
        out IntPtr PolicyHandle
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaAddAccountRights(
        LSA_HANDLE PolicyHandle,
        IntPtr pSID,
        LSA_UNICODE_STRING[] UserRights,
        int CountOfRights
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern int LsaLookupNames2(
        LSA_HANDLE PolicyHandle,
        uint Flags,
        uint Count,
        LSA_UNICODE_STRING[] Names,
        ref IntPtr ReferencedDomains,
        ref IntPtr Sids
        );

        [DllImport("advapi32")]
        internal static extern int LsaNtStatusToWinError(int NTSTATUS);

        [DllImport("advapi32")]
        internal static extern int LsaClose(IntPtr PolicyHandle);

        [DllImport("advapi32")]
        internal static extern int LsaFreeMemory(IntPtr Buffer);

    }
    /// <summary>
    /// This class is used to grant "Log on as a service", "Log on as a batchjob", "Log on localy" etc.
    /// to a user.
    /// </summary>
    public sealed class LsaWrapper : IDisposable
    {
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_TRUST_INFORMATION
        {
            internal LSA_UNICODE_STRING Name;
            internal IntPtr Sid;
        }
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_TRANSLATED_SID2
        {
            internal SidNameUse Use;
            internal IntPtr Sid;
            internal int DomainIndex;
            uint Flags;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct LSA_REFERENCED_DOMAIN_LIST
        {
            internal uint Entries;
            internal LSA_TRUST_INFORMATION Domains;
        }

        enum SidNameUse : int
        {
            User = 1,
            Group = 2,
            Domain = 3,
            Alias = 4,
            KnownGroup = 5,
            DeletedAccount = 6,
            Invalid = 7,
            Unknown = 8,
            Computer = 9
        }

        enum Access : int
        {
            POLICY_READ = 0x20006,
            POLICY_ALL_ACCESS = 0x00F0FFF,
            POLICY_EXECUTE = 0X20801,
            POLICY_WRITE = 0X207F8
        }
        const uint STATUS_ACCESS_DENIED = 0xc0000022;
        const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
        const uint STATUS_NO_MEMORY = 0xc0000017;

        IntPtr lsaHandle;

        public LsaWrapper()
            : this(null)
        { }
        // // local system if systemName is null
        public LsaWrapper(string systemName)
        {
            LSA_OBJECT_ATTRIBUTES lsaAttr;
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
            lsaHandle = IntPtr.Zero;
            LSA_UNICODE_STRING[] system = null;
            if (systemName != null)
            {
                system = new LSA_UNICODE_STRING[1];
                system[0] = InitLsaString(systemName);
            }

            uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
            (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void AddPrivileges(string account, string privilege)
        {
            IntPtr pSid = GetSIDInformation(account);
            LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
            privileges[0] = InitLsaString(privilege);
            uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void Dispose()
        {
            if (lsaHandle != IntPtr.Zero)
            {
                Win32Sec.LsaClose(lsaHandle);
                lsaHandle = IntPtr.Zero;
            }
            GC.SuppressFinalize(this);
        }
        ~LsaWrapper()
        {
            Dispose();
        }
        // helper functions

        IntPtr GetSIDInformation(string account)
        {
            LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
            LSA_TRANSLATED_SID2 lts;
            IntPtr tsids = IntPtr.Zero;
            IntPtr tdom = IntPtr.Zero;
            names[0] = InitLsaString(account);
            lts.Sid = IntPtr.Zero;
            //Console.WriteLine("String account: {0}", names[0].Length);
            int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids);
            if (ret != 0)
                throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret));
            lts = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(tsids,
            typeof(LSA_TRANSLATED_SID2));
            Win32Sec.LsaFreeMemory(tsids);
            Win32Sec.LsaFreeMemory(tdom);
            return lts.Sid;
        }

        static LSA_UNICODE_STRING InitLsaString(string s)
        {
            // Unicode strings max. 32KB
            if (s.Length > 0x7ffe)
                throw new ArgumentException("String too long");
            LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
            lus.Buffer = s;
            lus.Length = (ushort)(s.Length * sizeof(char));
            lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
            return lus;
        }
    }
    public class LsaWrapperCaller
    {
        public static void AddPrivileges(string account, string privilege)
        {
            using (LsaWrapper lsaWrapper = new LsaWrapper())
            {
                lsaWrapper.AddPrivileges(account, privilege);
            }
        }
    }
}
'@

Add-Type -TypeDefinition $Source | Out-Null


# -------------------------
# Пересоздание пользователя
# -------------------------
$UserName    = "Student"
$Password    = "Student"

Remove-Users | Out-Null
New-User $UserName $Password | Out-Null
Set-AutoLogon $UserName $Password | Out-Null
[MyLsaWrapper.LsaWrapperCaller]::AddPrivileges($UserName, "SeBatchLogonRight") | Out-Null
write-host "-- разрешен вход в качестве пакетного задания для пользователя $UserName" -foregroundcolor Green
schtasks /create /tn LogonUserSettings /tr "pwsh C:ScriptsSetupUser.ps1" /sc onlogon /ru $env:USERDOMAIN$UserName /rp $Password /f

Ejecutado bajo el usuario Student

Función Set-Proxy {
    <#
    .SYNOPSIS
        Configuración de parámetros del proxy
    .DESCRIPTION
        Esta función establece los parámetros del proxy para el usuario
    .EXAMPLE
        #Set-Proxy a.cproxy.ru 8080
    .PARAMETER Server
        Dirección o nombre de dominio del servidor (parámetro obligatorio)
    .PARAMETER Port
        Puerto (parámetro obligatorio)
    #>

    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Server,
        [PARAMETER(Mandatory=$True)][Int]$Port
        )

	If ((Test-NetConnection -ComputerName $Server -Port $Port).TcpTestSucceeded) {
		Set-ItemProperty -Path 'HKCU:SoftwareMicrosoftWindowsCurrentVersionInternet Settings' -name ProxyServer -Value "$($Server):$($Port)"
		Set-ItemProperty -Path 'HKCU:SoftwareMicrosoftWindowsCurrentVersionInternet Settings' -name ProxyEnable -Value 1
	} Else {
		Write-Error -Message "-- Dirección o puerto del servidor proxy inválido:  $($Server):$($Port)"
	}
}

Función Set-AccessRule {
    <#
    .SYNOPSIS
        Configuración de permisos en una carpeta
    .DESCRIPTION
        Esta función establece los permisos especificados en un directorio
    .EXAMPLE
        #Set-AccessRule -Folder $env:USERPROFILEDesktop  -UserName $env:USERNAME -Rules CreateFiles,AppendData -AccessControlType Deny
    .PARAMETER Folder
        Directorio sobre el cual se realiza la acción (parámetro obligatorio)
    .PARAMETER UserName
        Nombre de la cuenta de usuario para la que se establecen los permisos de acceso (parámetro obligatorio)
    .PARAMETER Rules
        Permisos de acceso separados por comas (parámetro obligatorio)
    .PARAMETER AccessControlType
        Parámetro obligatorio que puede aceptar uno de dos valores: Allow o Deny
    #>
    [CmdletBinding()]
    param (
        [PARAMETER(Mandatory=$True)][String]$Folder,
        [PARAMETER(Mandatory=$True)][String]$UserName,
        [PARAMETER(Mandatory=$True)][String]$Rules,
        [PARAMETER(Mandatory=$True)][String]$AccessControlType
        )

    #se lee la lista actual de ACL del escritorio
    $acl = Get-Acl $Folder
    #Se crea una variable con los permisos necesarios
    $fileSystemRights = [System.Security.AccessControl.FileSystemRights]"$Rules"
    #Se crea una variable que indica el usuario, los permisos de acceso y el tipo de autorización
    $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($UserName, $fileSystemRights, $AccessControlType)
    #Se pasa la variable a la clase FileSystemAccessRule para crear el objeto
    $acl.SetAccessRule($AccessRule)
    #Aplicar permisos a la carpeta
    $acl | Set-Acl $Folder
}

function Set-PinnedApplication
{
    <#
    .SYNOPSIS
        Gestión de accesos directos en la barra de tareas
    .DESCRIPTION
        Esta función añade o elimina accesos directos en la barra de tareas del usuario
    .EXAMPLE
        #Set-PinnedApplication -Action UnpinfromTaskbar -FilePath "$env:ProgramFilesInternet Exploreriexplore.exe"
    .EXAMPLE
        #Set-PinnedApplication -Action PintoTaskbar -FilePath "${env:ProgramFiles(x86)}Mozilla Firefoxfirefox.exe"
    .PARAMETER Action
        Parámetro obligatorio que puede aceptar uno de dos valores: UnpinfromTaskbar o PintoTaskbar
    .PARAMETER FilePath
        Nombre de la cuenta de usuario para la que se establecen los accesos directos (parámetro obligatorio)
    #>
    [CmdletBinding()]
    param(
            [Parameter(Mandatory=$True)][String]$Action, 
            [Parameter(Mandatory=$True)][String]$FilePath
    )
    if(-not (test-path $FilePath)) { 
        throw "FilePath no existe."  
    }
    function InvokeVerb {
        param([string]$FilePath,$verb)
        $verb = $verb.Replace("&","")
        $path = split-path $FilePath
        $shell = new-object -com "Shell.Application" 
        $folder = $shell.Namespace($path)   
        $item = $folder.Parsename((split-path $FilePath -leaf))
        $itemVerb = $item.Verbs() | ? {$_.Name.Replace("&","") -eq $verb}
        if($itemVerb -eq $null){
            throw "Verbo $verb no encontrado."           
        } else {
            $itemVerb.DoIt()
        }
    }
    function GetVerb {
        param([int]$verbId)
        try {
            $t = [type]"CosmosKey.Util.MuiHelper"
        } catch {
            $def = [Text.StringBuilder]""
            [void]$def.AppendLine('[DllImport("user32.dll")]')
            [void]$def.AppendLine('public static extern int LoadString(IntPtr h,uint id, System.Text.StringBuilder sb,int maxBuffer);')
            [void]$def.AppendLine('[DllImport("kernel32.dll")]')
            [void]$def.AppendLine('public static extern IntPtr LoadLibrary(string s);')
            Add-Type -MemberDefinition $def.ToString() -name MuiHelper -namespace CosmosKey.Util            
        }
        if($global:CosmosKey_Utils_MuiHelper_Shell32 -eq $null){        
            $global:CosmosKey_Utils_MuiHelper_Shell32 = [CosmosKey.Util.MuiHelper]::LoadLibrary("shell32.dll")
        }
        $maxVerbLength=255
        $verbBuilder = New-Object Text.StringBuilder "",$maxVerbLength
        [void][CosmosKey.Util.MuiHelper]::LoadString($CosmosKey_Utils_MuiHelper_Shell32,$verbId,$verbBuilder,$maxVerbLength)
        return $verbBuilder.ToString()
    }
    $verbs = @{ 
        "PintoTaskbar"=5386
        "UnpinfromTaskbar"=5387
    }
    if($verbs.$Action -eq $null){
        Throw "Acción $action no soportada`nLas acciones soportadas son:`n`tPintoTaskbar`n`tUnpinfromTaskbar"
    }
    InvokeVerb -FilePath $FilePath -Verb $(GetVerb -VerbId $verbs.$action)
}

Set-Proxy cproxy.udsu.ru 8080
Set-AccessRule -Folder $env:USERPROFILEDesktop  -UserName $env:USERNAME -Rules "CreateFiles,AppendData,Delete" -AccessControlType Deny

Set-PinnedApplication -Action UnpinfromTaskbar -FilePath "$env:ProgramFilesInternet Exploreriexplore.exe"
Set-PinnedApplication -Action PintoTaskbar -FilePath "${env:ProgramFiles(x86)}Mozilla Firefoxfirefox.exe"
Set-PinnedApplication -Action PintoTaskbar -FilePath "$env:ProgramDataMicrosoftWindowsStart MenuProgramsMicrosoft Office 2013Excel 2013.lnk"
Set-PinnedApplication -Action PintoTaskbar -FilePath "$env:ProgramDataMicrosoftWindowsStart MenuProgramsMicrosoft Office 2013Word 2013.lnk"
Set-PinnedApplication -Action PintoTaskbar -FilePath "$env:ProgramDataMicrosoftWindowsStart MenuProgramsMicrosoft Office 2013PowerPoint 2013.lnk"
Set-PinnedApplication -Action PintoTaskbar -FilePath "$env:ProgramDataMicrosoftWindowsStart MenuProgramsАСКОНКОМПАС-3D V16КОМПАС-3D V16.lnk"

# Eliminación de la tarea, después de su ejecución
Unregister-ScheduledTask -TaskName UdSUSettingStudent -Confirm:$false

Fuente: habr.com

Compra un hosting fiable para sitios web con protección contra DDoS, servidores VPS VDS 🔥 Compra un hosting fiable para sitios web con protección contra DDoS, servidores VPS VDS | ProHoster