Dark mode

Dark mode

There are 0 results matching

article card image dark article card image light

Published by · Jun 18, 2024 tools · 2 mins read

Introducing: Configuration Manager Set Implicit Uninstall Flag Tool

Setting Configuration Manager ConfigMgr Implicit Uninstall Flag with PowerShell for Required Application Deployments ...

See More
article card image dark article card image light

Published by · Jun 11, 2024 configmgr · 2 mins read

Configuration Manager Next Maintenance Window SQL Function

Get Next Configuration Manager Maintenance Window from a Schedule Token with Offset Days using an SQL Function. ...

See More
article card image dark article card image light

Published by · Jun 3, 2024 tools · 2 mins read

Introducing: Windows User Rights Assignment Tool - Part 3

Add, Remove, or Replace Windows Rights Assignment with our PowerShell Tool. ...

See More
article card image dark article card image light

Published by · May 28, 2024 tools · 2 mins read

Introducing: Windows User Rights Assignment Tool - Part 2

Get and Report Windows Rights Assignment with our PowerShell Tool. ...

See More
article card image dark article card image light

Published by · May 22, 2024 tools · 1 mins read

Introducing: Windows User Rights Assignment Tool - Part 1

Get Windows Rights Assignment with our PowerShell Tool. ...

See More
article card image dark article card image light

Published by · Apr 11, 2024 tools · 2 mins read

Introducing: Intune Linux Onboarding Tool

Onboard Ubuntu Linux devices to Microsoft Intune using a bash script. Installs prerequisites and starts the user-driven enrollment. ...

See More
article card image dark article card image light

Published by · Apr 11, 2024 tools · 2 mins read

Introducing: Intune macOS Onboarding Tool

Onboard macOS devices to Microsoft Intune using a bash script that initiates the process. Optionally, the script converts mobile accounts, resets the FileVault key, and removes ...

See More
article card image dark article card image light

Published by · Jan 23, 2024 tools · 3 mins read

Introducing: Intune Device Renaming Tool

Rename Intune Devices by setting a Prefix or using a User Attribute as Prefix. Supports Windows, macOS, and Linux ...

See More
article card image dark article card image light

Published by · Dec 8, 2023 intune · 5 mins read

Intune Logs: A Deep Dive into Locations, Interpretation, and Configuration

A Comprehensive Guide to Locations, Interpretation, and Configuration of Intune Logs ...

See More
article card image dark article card image light

Published by · Aug 14, 2023 configmgr · 2 mins read

Configuration Manager Console Extension to show Device Collection Membership with Console Builder

Use the Configuration Manager Console Builder, to add Collection Membership View to the Device Node ...

See More
article card image dark article card image light

Published by · Aug 3, 2023 tools · 3 mins read

Introducing: Configuration Manager SSRS Dashboards

A Configuration Manager Dashboards solution with Reports for Software Updates, Bitlocker and more ...

See More
article card image dark article card image light

Published by · Aug 3, 2023 tools · 2 mins read

Introducing: PowerShell WMI Management Toolkit Module

Streamline your WMI Namespace, Class, and Instance Management with our PowerShell Module ...

See More
article card image dark article card image light

Published by · Jul 14, 2023 configmgr · 1 mins read

Configuration Manager detailed, filterable Port Documentation

Configuration Manager detailed, filterable port documentation as an excel document ...

See More
article card image dark article card image light

Published by · Jul 14, 2023 configmgr · 3 mins read

Configuration Manager PXE TFTP Window Size Bug

Configuration Manager TFTP Block Size and TFTP Window Size Correct Configuration ...

See More
article card image dark article card image light

Published by · Jun 18, 2023 tools · 4 mins read

Introducing: Configuration Manager Client Cache Cleanup Tool

Cleaning the Configuration Manager Client Cache the Right Way with PowerShell and Configuration Baselines ...

See More
article card image dark article card image light

Published by · Jun 18, 2023 tools · 2 mins read

Introducing: Windows Cache Cleanup Tool

Cleaning Windows and Configuration Manager Caches for Configuration Manager Build and Capture Task Sequence or Standalone Use ...

See More
article card image dark article card image light

Published by · Jun 17, 2023 tools · 1 mins read

Introducing: Windows Update Database Reinitialization Tool

Proactively repair corrupted Windows Update Database with Powershell and Configuration Manager ...

See More
article card image dark article card image light

Published by · Mar 31, 2023 tools · 3 mins read

Introducing: Configuration Manager SQL Products Reporting

A Complete SQL Products reporting solution using Configuration Manager ...

See More
article card image dark article card image light

Published by · Jan 28, 2023 configmgr · 1 mins read

Application Detection Method using the Configuration Manager Application Version

Replace hardcoded application version in scripts, with the Configuration Manager Application Version ...

See More
article card image dark article card image light

Published by · Jan 28, 2023 tools · 3 mins read

Introducing: Certificate Management Toolkit

Managing Certificates with Configuration Manager and PowerShell by using just the Public Key ...

See More
article card image dark article card image light

Published by · Jan 7, 2019 reports · 2 mins read

Configuration Manager Device Boundary and Network Information Report

List Device Boundaries and Network Information with Configuration Manager ...

See More
article card image dark article card image light

Published by · Sep 9, 1980 help · 5 mins read

MEM.Zone Blog Publishing Documentation

Publishing Documentation for MEM.Zone ...

See More

We couldn’t find anything related to

“SCCM”

BLOG / tools zone

Introducing: Windows User Rights Assignment Tool - Part 3

Published by Popovici Ioan · Jun 3, 2024 · 2 mins read
article card image dark article card image light

Quick Summary

Managing User Rights Assignment is not always straight forward especially with Intune. To address this issue we have created a PowerShell tool to help you manage User Rights Assignment on Windows devices. This will be a three part series where we will cover getting, setting and writing User Rights Assignment to WMI for easy reporting.

Part 3 covers the Adding, Removing or Replacing of User Rights Assignments.

This tool can be used as a standalone script or integrated into your Configuration Manager or Intune Compliance Baseline or Script.

Prerequisites


Recommendations

  • Always use a test environment to validate your configuration.
  • History is available in the %SystemRoot%\Logs\Set-UserRightsAssignment\ folder.

Parameters

Action

  • Add
    Adds user rights assignment.
  • Replace
    Replaces user rights assignment.
  • Remove
    Removes user rights assignment.
  • RemoveAll
    Removes all user rights assignments for the specified principal.

Principal

Defines the Principal to get the rights for.

Privilege

Defines the User Right(s) to get the principals for.

Notes

If RemoveAll Action is specified, the Privilege parameter will be ignored.

If you use the Principal Name instead of a SID you need to localize your Principal Name with the locale of the OS this script will be running on.


Examples

Add Privilege to Principal

Set-UserRightsAssignment.ps1 -Add -Principal 'CONTOSO\User' -Privilege 'SeServiceLogonRight'

Remove Privilege for Principal

Set-UserRightsAssignment.ps1 -RemoveAll -Principal 'CONTOSO\Group'

Remove All Privileges for Principal

Set-UserRightsAssignment.ps1 -RemoveAll -Principal 'CONTOSO\Group'

Replace Privilege for Principal

Set-UserRightsAssignment.ps1 -Replace -Principal 'CONTOSO\Group' -Privilege 'SeServiceLogonRight'

Preview

article card image powershell-set-windows-user-rights-assignment.gif
Set User Rights Assignment

Code

  1<#
  2.SYNOPSIS
  3    Add, Replace or Remove user rights assignment.
  4.DESCRIPTION
  5    Add, Replace or Remove user rights assignment to a local computer.
  6.PARAMETER Action
  7    Specify the action to perform.
  8    Valid values:
  9        - Add       : Add user rights assignment.
 10        - Replace   : Replace user rights assignment.
 11        - Remove    : Remove user rights assignment.
 12        - RemoveAll : Remove all user rights assignments for the specified principal.
 13.PARAMETER Principal
 14    Defines the Principal under which the service should run.
 15    Default is the current user.
 16.PARAMETER Privilege
 17    Defines the User Right(s) you want to set. If 'RemoveAll' Action is specified, this parameter can't be set.
 18    Valid values are:
 19        SeAssignPrimaryTokenPrivilege
 20        SeAuditPrivilege
 21        SeBackupPrivilege
 22        SeChangeNotifyPrivilege
 23        SeCreateGlobalPrivilege
 24        SeCreatePagefilePrivilege
 25        SeCreatePermanentPrivilege
 26        SeCreateSymbolicLinkPrivilege
 27        SeCreateTokenPrivilege
 28        SeDebugPrivilege
 29        SeEnableDelegationPrivilege
 30        SeImpersonatePrivilege
 31        SeIncreaseBasePriorityPrivilege
 32        SeIncreaseQuotaPrivilege
 33        SeIncreaseWorkingSetPrivilege
 34        SeLoadDriverPrivilege
 35        SeLockMemoryPrivilege
 36        SeMachineAccountPrivilege
 37        SeManageVolumePrivilege
 38        SeProfileSingleProcessPrivilege
 39        SeRelabelPrivilege
 40        SeRemoteShutdownPrivilege
 41        SeRestorePrivilege
 42        SeSecurityPrivilege
 43        SeShutdownPrivilege
 44        SeSyncAgentPrivilege
 45        SeSystemEnvironmentPrivilege
 46        SeSystemProfilePrivilege
 47        SeSystemtimePrivilege
 48        SeTakeOwnershipPrivilege
 49        SeTcbPrivilege
 50        SeTimeZonePrivilege
 51        SeTrustedCredManAccessPrivilege
 52        SeUndockPrivilege
 53        SeUnsolicitedInputPrivilege
 54.EXAMPLE
 55    Set-UserRightsAssignment.ps1 -Add -Principal 'CONTOSO\User' -Privilege 'SeServiceLogonRight'
 56.EXAMPLE
 57    Set-UserRightsAssignment.ps1 -Add -Principal 'S-1-5-21-1234567890-1234567890-1234567890-500' -Privilege 'SeServiceLogonRight'
 58.EXAMPLE
 59    Set-UserRightsAssignment.ps1 -Remove -Principal 'CONTOSO\Group' -Privilege 'SeServiceLogonRight'
 60.EXAMPLE
 61    Set-UserRightsAssignment.ps1 -RemoveAll -Principal 'CONTOSO\Group'
 62.EXAMPLE
 63    Set-UserRightsAssignment.ps1 -Replace -Principal 'CONTOSO\Group' -Privilege 'SeServiceLogonRight'
 64.INPUTS
 65    None.
 66.OUTPUTS
 67    None.
 68.NOTES
 69    Created by Ioan Popovici
 70    Original script by Bill Loytty (weloytty)
 71.LINK
 72    https://MEMZ.one/Set-UserRightsAssignment
 73.LINK
 74    https://MEMZ.one/Set-UserRightsAssignment-CHANGELOG
 75.LINK
 76    https://MEMZ.one/Set-UserRightsAssignment-GIT
 77.LINK
 78    https://MEM.Zone/ISSUES
 79.LINK
 80    https://github.com/weloytty/QuirkyPSFunctions/blob/ab4b02f9cc05505eee97d2f744f4c9c798143af1/Source/Users/Grant-LogOnAsService.ps1
 81.COMPONENT
 82    User Rights Assignment
 83.FUNCTIONALITY
 84    Sets User Rights Assigment.
 85#>
 86
 87    [CmdletBinding()]
 88    Param (
 89        [Parameter(Mandatory = $true, HelpMessage = 'Add/Remove user right.', Position = 0)]
 90        [ValidateSet('Add', 'Remove', 'RemoveAll', 'Replace', IgnoreCase = $true)]
 91        [Alias('Task')]
 92        [string]$Action,
 93        [Parameter(Mandatory = $false, Position = 1)]
 94        [Alias('User')]
 95        [string]$Principal = -join ($env:USERDOMAIN, '\', $env:USERNAME)
 96    )
 97
 98    ## Declare dynamic parameter to be required if 'RemoveAll' action is not specified
 99    DynamicParam {
100        If ($Action -ne 'RemoveAll') {
101
102            ## Declare the PrivilegeList attribute value
103            [string[]]$PrivilegeList = @('SeNetworkLogonRight','SeBackupPrivilege','SeChangeNotifyPrivilege','SeSystemtimePrivilege','SeCreatePagefilePrivilege',
104                'SeDebugPrivilege','SeRemoteShutdownPrivilege','SeAuditPrivilege','SeIncreaseQuotaPrivilege','SeIncreaseBasePriorityPrivilege',
105                'SeLoadDriverPrivilege','SeBatchLogonRight','SeServiceLogonRight','SeInteractiveLogonRight','SeSecurityPrivilege',
106                'SeSystemEnvironmentPrivilege','SeProfileSingleProcessPrivilege','SeSystemProfilePrivilege','SeAssignPrimaryTokenPrivilege',
107                'SeRestorePrivilege','SeShutdownPrivilege','SeTakeOwnershipPrivilege','SeDenyNetworkLogonRight','SeDenyInteractiveLogonRight',
108                'SeUndockPrivilege','SeManageVolumePrivilege','SeRemoteInteractiveLogonRight','SeImpersonatePrivilege','SeCreateGlobalPrivilege',
109                'SeIncreaseWorkingSetPrivilege','SeTimeZonePrivilege','SeCreateSymbolicLinkPrivilege','SeDelegateSessionUserImpersonatePrivilege',
110                'SeMachineAccountPrivilege','SeTrustedCredManAccessPrivilege','SeTcbPrivilege','SeCreateTokenPrivilege','SeCreatePermanentPrivilege',
111                'SeDenyBatchLogonRight','SeDenyServiceLogonRight','SeDenyRemoteInteractiveLogonRight','SeEnableDelegationPrivilege',
112                'SeLockMemoryPrivilege','SeRelabelPrivilege','SeSyncAgentPrivilege'
113            )
114
115            ## Create a new ParameterAttribute Object
116            $ParameterAttribute = [System.Management.Automation.ParameterAttribute]::new()
117            #  Specify parameter attributes
118            $ParameterAttribute.Position = 2
119            $ParameterAttribute.Mandatory = $true
120
121            ## Create a new ValidateSetAttribute object
122            $ValidateSetAttribute = [System.Management.Automation.ValidateSetAttribute]::new($PrivilegeList)
123
124            ## Create an AttributeCollection object for the created attributes.
125            $AttributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
126
127            ## Add the Parameter Atributes
128            $AttributeCollection.Add($ParameterAttribute)
129            $AttributeCollection.Add($ValidateSetAttribute)
130
131            ## Add the paramater specifying the attribute collection
132            $PrivilegeParameter = [System.Management.Automation.RuntimeDefinedParameter]::new('Privilege', [string[]], $AttributeCollection)
133
134            ## Expose the name of the parameter
135            $ParamDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
136            $ParamDictionary.Add('Privilege', $PrivilegeParameter)
137
138            ## Return the dictionary object to the pipeline
139            Write-Output -InputObject $ParamDictionary
140        }
141    }
142
143##*=============================================
144##* VARIABLE DECLARATION
145##*=============================================
146#region VariableDeclaration
147
148## Get script path and name
149[string]$ScriptPath = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition)
150[string]$ScriptName = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition)
151
152## Set log file path
153[string]$LogFilePath = [System.IO.Path]::Combine($env:SystemRoot + '\Logs\', $ScriptName, $ScriptName + '.log')
154
155#endregion
156##*=============================================
157##* END VARIABLE DECLARATION
158##*=============================================
159
160##*=============================================
161##* FUNCTION LISTINGS
162##*=============================================
163#region FunctionListings
164
165#region Function Resolve-Principal
166Function Resolve-Principal {
167<#
168.SYNOPSIS
169    Resolves a Principal or Principals.
170.DESCRIPTION
171    Resolves a Principal or Principals to SID or Principal Name.
172.PARAMETER Principal
173    Specifies the Principal to resolve.
174.EXAMPLE
175    Resolve-Principal -Principal 'CONTOSO\User'
176.EXAMPLE
177    Resolve-Principal -Principal 'CONTOSO\User', 'CONTOSO\Group', 'BUILTIN\Administrators'
178.EXAMPLE
179    Resolve-Principal -Principal 'S-1-5-21-1234567890-1234567890-1234567890-500'
180.EXAMPLE
181    Resolve-Principal -Principal 'S-1-5-21-1234567890-1234567890-1234567890-500', 'S-1-5-21-1234567890-1234567890-1234567890-501'
182.INPUTS
183    System.Array
184.OUTPUTS
185    System.Object
186    System.Exception
187.NOTES
188    Created by Ioan Popovici
189.LINK
190    https://MEM.Zone
191.LINK
192    https://MEM.Zone/GIT
193.LINK
194    https://MEM.Zone/ISSUES
195.COMPONENT
196    Security Principal
197.FUNCTIONALITY
198    Resolves a Principal or Principals to SID or Principal Name.
199#>
200    [CmdletBinding()]
201    Param (
202        [Parameter(Mandatory = $true, Position = 0)]
203        [ValidateNotNullorEmpty()]
204        [Alias('SecurityPrincipal')]
205        [string[]]$Principal
206    )
207    Begin {
208
209        ## Set SID regex match Pattern
210        [regex]$Pattern = 'S-\d-(?:\d+-){1,14}\d+'
211
212        ## Initialize output object
213        $Output = $null
214    }
215    Process {
216        Try {
217
218            ## Resolve Principal
219            $Output = ForEach ($PrincipalItem in $Principal) {
220                Try {
221                    #  Set Principal type
222                    [string]$SIDMatch = (Select-String -Pattern $Pattern -InputObject $PrincipalItem).Matches.Value
223                    [string]$PrincipalType = If ([string]::IsNullOrEmpty($SIDMatch)) { 'PrincipalName' } Else { 'PrincipalSID' }
224                    #  Resolve Principal
225                    Switch ($PrincipalType) {
226                        'PrincipalName' {
227                            Write-Warning -Message 'You specified a Principal Name. This is not recommended if the names are not localized for the OS this script will be running on. Please use SID instead.'
228                            $NTAccountObject = New-Object System.Security.Principal.NTAccount($PrincipalItem)
229                            $NTAccountObject.Translate([System.Security.Principal.SecurityIdentifier]).Value
230                            Break
231                        }
232                        'PrincipalSID' {
233                            $SIDObject = New-Object System.Security.Principal.SecurityIdentifier($PrincipalItem.Replace('*',''))
234                            $SIDObject.Translate([Security.Principal.NTAccount]).Value
235                            Break
236                        }
237                    }
238                }
239                Catch {
240
241                    ## Return custom error. The error handling is done here in order not to break the ForEach loop and allow it to continue.
242                    $Exception     = [Exception]::new($PsItem.Exception.Message)
243                    $ExceptionType = [Management.Automation.ErrorCategory]::ObjectNotFound
244                    $ErrorRecord   = [System.Management.Automation.ErrorRecord]::new($Exception, $PsItem.FullyQualifiedErrorId, $ExceptionType, $PrincipalItem)
245                    $PSCmdlet.WriteError($ErrorRecord)
246                }
247            }
248        }
249        Catch {
250            $PSCmdlet.WriteError($PSItem)
251        }
252        Finally {
253            Write-Output -InputObject $Output
254        }
255    }
256}
257#endregion
258
259#region Function Set-UserRightsAssignment
260Function Set-UserRightsAssignment {
261<#
262.SYNOPSIS
263    Add, Replace or Remove user rights assignment.
264.DESCRIPTION
265    Add, Replace or Remove user rights assignment to a local computer.
266.PARAMETER Action
267    Specify the action to perform.
268    Valid values:
269        - Add       : Add user rights assignment.
270        - Replace   : Replace user rights assignment.
271        - Remove    : Remove user rights assignment.
272        - RemoveAll : Remove all user rights assignments for the specified principal.
273.PARAMETER Principal
274    Defines the Principal under which the service should run.
275    Default is the current user.
276.PARAMETER Privilege
277    Defines the User Right(s) you want to set. If 'RemoveAll' Action is specified, this parameter can't be set.
278    Valid values are:
279        SeAssignPrimaryTokenPrivilege
280        SeAuditPrivilege
281        SeBackupPrivilege
282        SeChangeNotifyPrivilege
283        SeCreateGlobalPrivilege
284        SeCreatePagefilePrivilege
285        SeCreatePermanentPrivilege
286        SeCreateSymbolicLinkPrivilege
287        SeCreateTokenPrivilege
288        SeDebugPrivilege
289        SeEnableDelegationPrivilege
290        SeImpersonatePrivilege
291        SeIncreaseBasePriorityPrivilege
292        SeIncreaseQuotaPrivilege
293        SeIncreaseWorkingSetPrivilege
294        SeLoadDriverPrivilege
295        SeLockMemoryPrivilege
296        SeMachineAccountPrivilege
297        SeManageVolumePrivilege
298        SeProfileSingleProcessPrivilege
299        SeRelabelPrivilege
300        SeRemoteShutdownPrivilege
301        SeRestorePrivilege
302        SeSecurityPrivilege
303        SeShutdownPrivilege
304        SeSyncAgentPrivilege
305        SeSystemEnvironmentPrivilege
306        SeSystemProfilePrivilege
307        SeSystemtimePrivilege
308        SeTakeOwnershipPrivilege
309        SeTcbPrivilege
310        SeTimeZonePrivilege
311        SeTrustedCredManAccessPrivilege
312        SeUndockPrivilege
313        SeUnsolicitedInputPrivilege
314.EXAMPLE
315    Set-UserRightsAssignment -Add -Principal 'CONTOSO\User' -Privilege 'SeServiceLogonRight'
316.EXAMPLE
317    Set-UserRightsAssignment -Add -Principal 'S-1-5-21-1234567890-1234567890-1234567890-500' -Privileges 'SeServiceLogonRight'
318.EXAMPLE
319    Set-UserRightsAssignment -Remove -Principal 'CONTOSO\Group' -Privilege 'SeServiceLogonRight'
320.EXAMPLE
321    Set-UserRightsAssignment -RemoveAll -Principal 'CONTOSO\Group'
322.EXAMPLE
323    Set-UserRightsAssignment -Replace -Principal 'CONTOSO\Group' -Privilege 'SeServiceLogonRight'
324.INPUTS
325    None.
326.OUTPUTS
327    System.Object
328    System.Exception
329.NOTES
330    Created by Ioan Popovici
331.LINK
332    https://MEM.Zone
333.LINK
334    https://MEM.Zone/GIT
335.LINK
336    https://MEM.Zone/ISSUES
337.COMPONENT
338    User Rights Assignment
339.FUNCTIONALITY
340    Sets User Rights Assignment.
341#>
342    [CmdletBinding()]
343    Param (
344        [Parameter(Mandatory = $true, HelpMessage = 'Add/Remove user right.', Position = 0)]
345        [ValidateSet('Add', 'Remove', 'RemoveAll', 'Replace', IgnoreCase = $true)]
346        [Alias('Task')]
347        [string]$Action,
348        [Parameter(Mandatory = $false, Position = 1)]
349        [Alias('User')]
350        [string]$Principal = -join ($env:USERDOMAIN, '\', $env:USERNAME)
351    )
352
353    ## Declare dynamic parameter to be required if 'RemoveAll' action is not specified
354    DynamicParam {
355        If ($Action -ne 'RemoveAll') {
356
357            ## Declare the PrivilegeList attribute value
358            [string[]]$PrivilegeList = @('SeNetworkLogonRight','SeBackupPrivilege','SeChangeNotifyPrivilege','SeSystemtimePrivilege','SeCreatePagefilePrivilege',
359                'SeDebugPrivilege','SeRemoteShutdownPrivilege','SeAuditPrivilege','SeIncreaseQuotaPrivilege','SeIncreaseBasePriorityPrivilege',
360                'SeLoadDriverPrivilege','SeBatchLogonRight','SeServiceLogonRight','SeInteractiveLogonRight','SeSecurityPrivilege',
361                'SeSystemEnvironmentPrivilege','SeProfileSingleProcessPrivilege','SeSystemProfilePrivilege','SeAssignPrimaryTokenPrivilege',
362                'SeRestorePrivilege','SeShutdownPrivilege','SeTakeOwnershipPrivilege','SeDenyNetworkLogonRight','SeDenyInteractiveLogonRight',
363                'SeUndockPrivilege','SeManageVolumePrivilege','SeRemoteInteractiveLogonRight','SeImpersonatePrivilege','SeCreateGlobalPrivilege',
364                'SeIncreaseWorkingSetPrivilege','SeTimeZonePrivilege','SeCreateSymbolicLinkPrivilege','SeDelegateSessionUserImpersonatePrivilege',
365                'SeMachineAccountPrivilege','SeTrustedCredManAccessPrivilege','SeTcbPrivilege','SeCreateTokenPrivilege','SeCreatePermanentPrivilege',
366                'SeDenyBatchLogonRight','SeDenyServiceLogonRight','SeDenyRemoteInteractiveLogonRight','SeEnableDelegationPrivilege',
367                'SeLockMemoryPrivilege','SeRelabelPrivilege','SeSyncAgentPrivilege'
368            )
369
370            ## Create a new ParameterAttribute Object
371            $ParameterAttribute = [System.Management.Automation.ParameterAttribute]::new()
372
373            #  Specify parameter attributes
374            $ParameterAttribute.Position = 2
375            $ParameterAttribute.Mandatory = $true
376
377            ## Create a new ValidateSetAttribute object
378            $ValidateSetAttribute = [System.Management.Automation.ValidateSetAttribute]::new($PrivilegeList)
379
380            ## Create an AttributeCollection object for the created attributes.
381            $AttributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
382
383            ## Add the Parameter Atributes
384            $AttributeCollection.Add($ParameterAttribute)
385            $AttributeCollection.Add($ValidateSetAttribute)
386
387            ## Add the paramater specifying the attribute collection
388            $PrivilegeParameter = [System.Management.Automation.RuntimeDefinedParameter]::new('Privilege', [string[]], $AttributeCollection)
389
390            ## Expose the name of the parameter
391            $ParamDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
392            $ParamDictionary.Add('Privilege', $PrivilegeParameter)
393
394            ## Return the dictionary object to the pipeline
395            Write-Output -InputObject $ParamDictionary
396        }
397    }
398    Begin {
399
400        ## Set paths
401        $Path = [System.IO.Path]
402        [string]$TempFolderPath = $Path::GetTempPath()
403        [scriptblock]$RandomFileName = { $Path::GetRandomFileName() }
404        [string]$ExportFilePath = Join-Path -Path $TempFolderPath -ChildPath $Path::ChangeExtension($RandomFileName.Invoke(),'.ini')
405        [string]$ImportFilePath = Join-Path -Path $TempFolderPath -ChildPath $Path::ChangeExtension($RandomFileName.Invoke(),'.ini')
406        [string]$SecedtFilePath = Join-Path -Path $TempFolderPath -ChildPath $Path::ChangeExtension($RandomFileName.Invoke(),'.sdb')
407        [string]$System32Path   = [Environment]::GetFolderPath([Environment+SpecialFolder]::System)
408
409        ## Set output Object
410        $Result = [ordered]@{
411            PrincipalSID  = 'N/A'
412            PrincipalName = $Principal
413            Privilege     = 'N/A'
414            Action        = $Action
415            Operation     = 'N/A'
416        }
417
418        ## Set the Privilege variable according to the action
419        If ($Action -eq 'RemoveAll') {
420            $Privilege = $PrivilegeList
421            $Action = 'Remove'
422        }
423        Else {
424            #  Set the Privilege variable to the bound parameter, otherwise it will be $null
425            $Privilege = $PSBoundParameters['Privilege']
426        }
427        #  Set preliminary Result privilege
428        $Result.Privilege = $Privilege
429
430        ## Set SID regex match Pattern
431        [regex]$Pattern = 'S-\d-(?:\d+-){1,14}\d+'
432
433        ## Initialize output object
434        $Output = @()
435    }
436    Process {
437        Try {
438
439            ## Check for Admin Rights
440            [boolean]$IsAdministrator = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
441            If (-not $IsAdministrator) { Throw 'You must have administrative privileges to run this script!' }
442
443            ## Set ScEdit.exe path
444            [string]$SecEdit = Join-Path -Path $System32Path -ChildPath 'SecEdit.exe' -Resolve
445
446            ## Export current user rights
447            $null = & $SecEdit /export /cfg $ExportFilePath
448
449            ## Check if Principal is SID
450            [string]$SIDMatch = (Select-String -Pattern $Pattern -InputObject $Principal).Matches.Value
451            If ([string]::IsNullOrEmpty($SIDMatch)) {
452                $SID = Resolve-Principal -Principal $Principal -ErrorAction 'Stop'
453                #  Set output Object
454                $Result.PrincipalSID = $SID
455            }
456            Else {
457                $SID = $Principal
458                $Principal = Resolve-Principal -Principal $SID -ErrorAction 'SilentlyContinue'
459                #  Set output Object
460                $Result.PrincipalName = $Principal
461                $Result.PrincipalSID = $SID
462            }
463
464            ## Set user rights
465            $Output = ForEach ($PrivilegeItem in $Privilege) {
466
467                ## Set output Object
468                $Result.Privilege = $PrivilegeItem
469
470                ## Export current user rights
471                $null = & $SecEdit /export /cfg $ExportFilePath
472
473                ## Select the user right to modify
474                $SIDs = (Select-String $ExportFilePath -Pattern $PrivilegeItem).Line
475
476                ## Add or remove user right to the SIDList to be imported
477                Switch ($Action) {
478                    'Add'     { $SIDList = '{0},*{1}' -f $SIDs, $SID; Break }
479                    'Remove'  { $SIDList = $($SIDs.Replace("*$SID", '').Replace($Principal, '').Replace(',,', ',').Replace('= ,', '= ')); Break }
480                    'Replace' { $SIDList = '{0} = *{1}' -f $PrivilegeItem, $SID; Break }
481                }
482
483                ## Assemble the import file to use with secedit
484                $Lines = @('[Unicode]', 'Unicode=yes', '[System Access]', '[Event Audit]', '[Registry Values]', '[Version]', "Signature=`"`$CHICAGO$`"", 'Revision=1', '[Profile Description]', "Description=$Action $PrivilegeItem for $Principal", "[Privilege Rights]", "$SIDList")
485                ForEach ($Line in $Lines) { Add-Content -Path $ImportFilePath -Value $Line }
486
487                ## Use secedit to set user rights by importing the previously created import file
488                $null = & $SecEdit /import /db $SecedtFilePath /cfg $ImportFilePath
489                $null = & $SecEdit /configure /db $SecedtFilePath
490
491                ## Cleanup
492                Remove-Item -Path $ImportFilePath -Force -ErrorAction 'SilentlyContinue'
493                Remove-Item -Path $SecedtFilePath -Force -ErrorAction 'SilentlyContinue'
494
495                ## Return results
496                $Result.Operation = 'Successful'
497                [pscustomobject]$Result
498            }
499        }
500        Catch {
501            $Result.Operation = 'Failed'
502            $Output += [pscustomobject]$Result
503
504            ## Return custom error. The error handling is done here in order not to break the ForEach loop and allow it to continue.
505            $Message       = [string]"Error granting '{0}' to '{1}' on '{2}'!`n{3}" -f $($Result.Privilege), $Principal, $env:COMPUTERNAME, $($PsItem.Exception.Message)
506            $Exception     = [Exception]::new($Message)
507            $ExceptionType = [Management.Automation.ErrorCategory]::OperationStopped
508            $ErrorRecord   = [System.Management.Automation.ErrorRecord]::new($Exception, $PsItem.FullyQualifiedErrorId, $ExceptionType, $PrincipalItem)
509            $PSCmdlet.ThrowTerminatingError($ErrorRecord)
510        }
511        Finally {
512            Write-Output -InputObject $Output
513        }
514    }
515    End {
516        Remove-Item -Path $ExportFilePath -Force -ErrorAction 'SilentlyContinue'
517    }
518}
519#endregion
520
521#endregion
522##*=============================================
523##* END FUNCTION LISTINGS
524##*=============================================
525
526##*=============================================
527##* SCRIPT BODY
528##*=============================================
529#region ScriptBody
530
531## Write verbose info
532Write-Verbose -Message $("Script '{0}\{1}' started." -f $ScriptPath, $ScriptName) -Verbose
533
534## Start logging
535Start-Transcript -Path $LogFilePath -Append -Force
536
537## Set the Privilege variable according to the action
538If ($PSBoundParameters['Action'] -eq 'RemoveAll') {
539    $Privilege = $PrivilegeList
540    $Action = 'Remove'
541}
542Else {
543    #  Set the Privilege variable to the bound parameter, otherwise it will be $null
544    $Privilege = $PSBoundParameters['Privilege']
545}
546
547## Execute scriptblock
548$Output = Set-UserRightsAssignments -Principal $Principal -Privilege $Privilege -Action $Action
549
550## Write output
551Write-Output -InputObject $Output
552
553## Stop logging
554Stop-Transcript
555
556## Write verbose info
557Write-Verbose -Message $("Script '{0}\{1}' completed." -f $ScriptPath, $ScriptName) -Verbose
558
559## Handle exit codes for proactive remediations
560If ($Output -contains 'Failed') { Exit 1 }
561Else { Exit 0 }
562
563#endregion
564##*=============================================
565##* END SCRIPT BODY
566##*=============================================

SHARE

article card image dark article card image light

Published by · May 28, 2024 tools · 2 mins read

Introducing: Windows User Rights Assignment Tool - Part 2

Get and Report Windows Rights Assignment with our PowerShell Tool. ...

See More
article card image dark article card image light

Published by · May 22, 2024 tools · 1 mins read

Introducing: Windows User Rights Assignment Tool - Part 1

Get Windows Rights Assignment with our PowerShell Tool. ...

See More