Set and Check User Rights Assignment via PowerShell

You can add, remove, and check user rights assignment (remotely / locally) with the following powershell scripts..

Posted by : blakedrumm on Jan 5, 2022

powershell get user rights assignment

Local Computer

Remote computer, output types.

This post was last updated on October 11th, 2024

I stumbled across this gem ( weloytty/Grant-LogonAsService.ps1 ) that allows you to grant Logon as a Service Right for a User. I modified the script you can now run the Powershell script against multiple machines, users, and user rights.

Set User Rights

How to get it.

:arrow_left:

All of the User Rights that can be set:

Note You may edit line 558 in the script to change what happens when the script is run without any arguments or parameters, this also allows you to change what happens when the script is run from the PowerShell ISE.

Here are a few examples:

Add Users Single Users Example 1 Add User Right “Allow log on locally” for current user: . \Set-UserRights.ps1 -AddRight -UserRight SeInteractiveLogonRight Example 2 Add User Right “Log on as a service” for CONTOSO\User: . \Set-UserRights.ps1 -AddRight -Username CONTOSO\User -UserRight SeServiceLogonRight Example 3 Add User Right “Log on as a batch job” for CONTOSO\User: . \Set-UserRights.ps1 -AddRight -Username CONTOSO\User -UserRight SeBatchLogonRight Example 4 Add User Right “Log on as a batch job” for user SID S-1-5-11: . \Set-UserRights.ps1 -AddRight -Username S-1-5-11 -UserRight SeBatchLogonRight Add Multiple Users / Rights / Computers Example 5 Add User Right “Log on as a service” and “Log on as a batch job” for CONTOSO\User1 and CONTOSO\User2 and run on, local machine and SQL.contoso.com: . \Set-UserRights.ps1 -AddRight -UserRight SeServiceLogonRight , SeBatchLogonRight -ComputerName $ env : COMPUTERNAME , SQL.contoso.com -UserName CONTOSO\User1 , CONTOSO\User2
Remove Users Single Users Example 1 Remove User Right “Allow log on locally” for current user: . \Set-UserRights.ps1 -RemoveRight -UserRight SeInteractiveLogonRight Example 2 Remove User Right “Log on as a service” for CONTOSO\User: . \Set-UserRights.ps1 -RemoveRight -Username CONTOSO\User -UserRight SeServiceLogonRight Example 3 Remove User Right “Log on as a batch job” for CONTOSO\User: . \Set-UserRights.ps1 -RemoveRight -Username CONTOSO\User -UserRight SeBatchLogonRight Example 4 Remove User Right “Log on as a batch job” for user SID S-1-5-11: . \Set-UserRights.ps1 -RemoveRight -Username S-1-5-11 -UserRight SeBatchLogonRight Remove Multiple Users / Rights / Computers Example 5 Remove User Right “Log on as a service” and “Log on as a batch job” for CONTOSO\User1 and CONTOSO\User2 and run on, local machine and SQL.contoso.com: . \Set-UserRights.ps1 -RemoveRight -UserRight SeServiceLogonRight , SeBatchLogonRight -ComputerName $ env : COMPUTERNAME , SQL.contoso.com -UserName CONTOSO\User1 , CONTOSO\User2

Check User Rights

In order to check the Local User Rights, you will need to run the above (Get-UserRights), you may copy and paste the above script in your PowerShell ISE and press play.

UserAccountsRights

Note You may edit line 494 in the script to change what happens when the script is run without any arguments or parameters, this also allows you to change what happens when the script is run from the PowerShell ISE.

Get Local User Account Rights and output to text in console:

Get Remote SQL Server User Account Rights:

Get Local Machine and SQL Server User Account Rights:

Output Local User Rights on Local Machine as CSV in ‘C:\Temp’:

Output to Text in ‘C:\Temp’:

PassThru object to allow manipulation / filtering:

:v:

I like to collaborate and work on projects. My skills with Powershell allow me to quickly develop automated solutions to suit my customers, and my own needs.

Email : [email protected]

Website : https://blakedrumm.com

My name is Blake Drumm, I am working on the Azure Monitoring Enterprise Team with Microsoft. Currently working to update public documentation for System Center products and write troubleshooting guides to assist with fixing issues that may arise while using the products. I like to blog on Operations Manager and Azure Automation products, keep checking back for new posts. My goal is to post atleast once a month if possible.

  • operationsManager
  • troubleshooting
  • certificates
  • containerapps

4sysops

  • IT Administration Forum
  • PowerShell Forum
  • Community Forum
  • PowerShell Group
  • Earning as 4sysops member
  • Member Ranks
  • Member Leaderboard – This Month
  • Member Leaderboard – This Year
  • Member Leaderboard – All-time
  • Author Leaderboard – 30 Days
  • Author Leaderboard – 365 Days
  • Cloud Computing
  • Write for 4sysops

Display access rights on Active Directory OUs with PowerShell

4sysops - The online community for SysAdmins and DevOps

Avatar

Accessing AD as a drive

Recursive analysis of ous.

  • Recent Posts

Wolfgang Sommergut

  • Group Policy for Office 2024: New settings since 2021 LTSC - Tue, Oct 22 2024
  • Fix public Wi-Fi error “msftconnecttest.com– This site can’t be reached” - Tue, Oct 15 2024
  • Build a Windows Server 2025 S2D cluster lab with Hyper-V and PowerShell - Thu, Oct 10 2024

Delegating administrative tasks to standard users or inconsistently assigning user rights can result in users or groups having an unnecessarily powerful rights set. This enables them to damage the directory with improper or malicious activities and might give them unauthorized access to sensitive corporate data.

For this reason, it is recommended to regularly examine the AD rights structure. Various third-party tools exist for this purpose, and many allow you to monitor the directory in real time.

If you have fewer demands, you can use the free AD ACL Scanner , which uses the built-in PowerShell cmdlets. Of course, you can also directly work with PowerShell to query rights on AD objects.

The following examples demonstrate how you can display who has specific rights on an OU. First, you have to load the ActiveDirectory module. You can then navigate to the desired domain in the PowerShell AD drive:

For instance, if you want to find the users who have write access on the domain controllers OU, you can use the next command:

Displaying write access rights on the domain controllers OU

Displaying write access rights on the domain controllers OU

In this case, you can omit the domain for the -Path parameter because the domain controllers OU is located directly below the current directory and it is therefore sufficient to use a relative path. Otherwise, you would have to specify the complete distinguished name in the format "OU=Domain Controllers,DC=contoso,DC=com."

The question mark is the alias for Where-Object and ensures in the above example that only entries with rights containing the string “write” are displayed.

If the output is complex, you can pipe it to the Out-GridView cmdlet to display a table of AD attributes for better readability.

Displaying a table of AD attributes with Out-GridView

Displaying a table of AD attributes with Out-GridView

If you don’t just want to analyze a single OU, you can work with Get-ChildItem to recursively read the OUs of an entire domain. A filter allows you to restrict the output to objects of a certain type.

With the help of the function Get-OURights (see below), you can then read the access rights in a similar way as with the above command. The nested foreach loops iterate through the OUs and their ACLs.

When you call the function, you have to pass the name of the privilege that you want to retrieve to the parameter $Right . You can also work with the wildcard “*” here. The output uses the CSV format, which allows you to import the data to Excel.

For instance, the following command finds the users who have one of the write access rights in the domain.

Finding the users who have write access rights in the domain

Finding the users who have write access rights in the domain

Before you execute the command, you have to navigate to the domain’s AD drive. This MSDN page

IT Administration News

  • Anthropic AI agents: Automate using GUIs
  • Anthropic launches updated Claude 3.5 Sonnet model that beats GPT-4o and Gemini 1.5 Pro – Neowin
  • Windows 11 24H2 installs updates much faster thanks to Windows Update improvements – Neowin
  • Exploit released for new Windows Server “WinReg” NTLM Relay attack
  • Microsoft Announces Public Preview of AI Agents in Copilot Studio

Read All IT Administration News

Join the 4sysops PowerShell group!

Your question was not answered? Ask in the PowerShell forum!

View Active Directory Ports with PowerShell

Get Active Directory ports with PowerShell

Avatar

Group Policy for Office 2024: New settings since 2021 LTSC

Converting a Premium SSD disk to Premium SSD v2

Convert to Azure Premium SSD v2 Disks with PowerShell

Avatar

Protecting Active Directory from compromised passwords with Enzoic 3.5

Avatar

Authd: Cloud-Based OIDC authentication for Ubuntu Linux

Avatar

Build a Windows Server 2025 S2D cluster lab with Hyper-V and PowerShell

Planned failover progress can be monitored in Azure Portal

Customer Managed Planned Failover for Azure Storage using PowerShell

The Reference Spreadsheet allows filtering by Windows 11 version, but the data is inaccurate

Windows 11 24H2 Group Policy: 81 new settings for SMB, updates, printing, Defender, and more

Easy365Manager integrates into Active Directory Users and Computers (ADUC)

Manage Microsoft 365 from Active Directory Users and Computers (ADUC) with Easy365Manager

Key package in the ADSI-Editor.

Recover data from corrupted BitLocker drives with repair-bde and key packages

Overview of fine grained password policies in the Active Directory Administrative Center

Determine effective password policy for AD users with PowerShell

Displaying the scratchpad in the current terminal

New in Windows Terminal: Restore buffers, code snippets, scratchpad and regex

Attack surface Analyzer for Active Directory

Active Directory auditing with ManageEngine ADAudit Plus

Group Policy setting for notifying users about an expiring password

Send email notifications about expiring Active Directory passwords with a PowerShell script

Query the GUID for a password using manage-bde

Unlock BitLocker drive from Windows PE with a PowerSell script

Azure AD PowerShell seamlessly integrates with Entra PowerShell within a single PowerShell session

Microsoft Entra PowerShell module, successor to the Azure AD PowerShell module

Avatar

Receive critical Microsoft security alerts by email

Standard development tools are pre-installed in the CloudShell environment

Install AWS CloudShell in a VPC

Avatar

Delegated Managed Service Accounts in Windows Server 2025

Avatar

Audit Group Policy changes in the event log using XML queries and PowerShell

Avatar

how do i get the security on the root of the domain instead of an OU inside the domain. 

Avatar

Set-Location AD:

Avatar

I should imagine this will give you a domain ACL

DC=contoso,DC=com

Leave a reply Click here to cancel the reply

Please enclose code in pre tags: <pre></pre>

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

Receive new post notifications

Twitter

Subscribe to Newsletter

Follow 4sysops.

Please ask IT administration questions in the forums . Any other messages are welcome.

Log in with your credentials

or      Create an account

Forgot your details?

Create account.

powershell get user rights assignment

Managing User Rights in Powershell

' src=

Managing User Rights Assignments in Powershell

Windows User Rights, also known as Windows Privileges, are traditionally managed via GPO or in the simplest of cases via the server’s Local Security Policy. These assignments control special permissions that are often needed by IIS applications or other application hosting on Windows Servers.

So how can we manage these assignments in Powershell? There’s no obvious solution provided in Powershell, but there are several options are available. None of which are a pure Powershell solution, but some are close.

  • Wrap the ntrights.exe process in Powershell. This is relatively simple, but the downside is having an external dependency on the ntrights.exe file.
  • Embed a wrapper class to the LSA API in your script. This is a pretty good solution but certainly bloats your script.
  • Load and Reference the Carbon DLL (If you haven’t already checked out this Powershell library, you should it is very powerful and regularly updated. I choose this approach because it keeps the script clean and compact, it returns an array of strings for easy interrogation. It does require a dependency on carbon.dll, but this library provides a ton of functionality beyond just this.

I like the 3rd option, its very clean, and I like working with the Carbon library.

Now lets take this script to the next level and wrap it into a DSC Script implementation. We can use this same logic in a DSC configuration to make sure our desired User Rights Assignments are kept in place.

What else can we do? We could also create a Custom DSC Resource to have a cleaner DSC Configuration.

Related Posts

powershell get user rights assignment

Local Administrator Audit Script

powershell get user rights assignment

Powershell Log Archival Script

My new stories.

powershell get user rights assignment

powershell get user rights assignment

  • PowerShell Forum Directory
  • Publications

Managing Privileges using PoshPrivilege

A recent project of mine has been to write a module to manage privileges on a local system. What I came up is a module called PoshPrivilege that allows you to not only look at what user rights are available on a local or remote system, but also provide the ability to Add, Remove, Enable and Disable the privileges as well.

If you are running PowerShell V5, you can download this module from the PowerShell Gallery:

Otherwise, check out my GitHub page where I am maintaining this project:

https://github.com/proxb/PoshPrivilege

I won’t spend time talking about how I wrote this module and my reasons behind it. What I will say is that instead of writing out C# code and then using Add-Type to compile it, I went with the Reflection approach of building out everything from the pinvoke signatures for methods to the Structs and even the Enums.

Let’s get started by looking at what is available in this module. The first function that is available is Get-Privilege and it comes with a few parameters. This function’s purpose is to let you view what privileges are currently available on the system (local or remote) as well as what is currently applied to your current process token.

image

A quick run through of using this function with various parameters:

image

If this one looks familiar, then it is probably likely that you have used the following command:

image

I opted for boolean values instead to determine the state for easier filtering if needed.

Up next are the Enable/Disable-Privilege functions. These work to Enable or Disable the privileges that are currently available on your local system to your process token. This means that if something like SeDebugPrivilege isn’t available on your system (such as being removed via Group Policy), then you cannot use Enable-Privilege to add your process token to this privilege. As in the previous image where we can see what is enabled and disabled, these are the only privileges that are available for me to work with.

To show this point, I am going to enable both SeSecurityPrivilege and SeDebugPrivilege so you can see that while the first privilege will show as Enabled, the other will not appear as it has not been made available.

SNAGHTMLd2422

As you can see from the picture, SeSecurityPrivilege has been enabled as expected, but SeDebugPrivilege is nowhere to be found. If we want SeDebugPrivilege, we will need to go about this another way which will be shown shortly.

Disabling a privilege can be done using Disable-Privilege as shown in the example below.

SNAGHTMLfdf1c

Now that I have covered Enabling and Disabling of the privileges and their limitations, I will move onto the Add/Remove-Privilege functions which allow you to add a privilege for a user or group or remove them on a local system. Note that this only works up until it gets reverted if set by group policy. This will also note show up if you look at the privileges available on your current process token (you will log off and log back in to see it).

Remember that I do not have SeDebugPrivilege available to use? Well, now we can add it to my own account using Add-Privilege.

image

We can see it is now available, but as I mentioned before, it doesn’t show up in my current process. A logoff and login now shows that it is not only available, but already enabled.

image

With this now enabled, we could disable it as well if needed using Disable-Privilege. I added my account for show, but we can also add groups this was as well.

As with Adding a privilege, we can remove privileges as well using Remove-Privilege.

image

As with Add-Privilege, you will need to log off and log back in to see the change take effect on your account.

Again, you can install this module using Install-Module if running PowerShell V5 and this project is out on GitHub to download (and contribute to as well). Enjoy!

Share this:

4 responses to managing privileges using poshprivilege.

' src=

I downloaded the scripts from Github, but getting compile errors.

Specifically the errors are around the WInOS Structures listed below:

Unable to find type [LUID]: make sure that the assembly containing this type is loaded. Unable to find type [LSA_UNICODE_STRING]: make sure that the assembly containing this type is loaded. Unable to find type [LARGE_INTEGER]: make sure that the assembly containing this type is loaded. Unable to find type [LUID_AND_ATTRIBUTES]: make sure that the assembly containing this type is loaded. Unable to find type [TokPriv1Luid]: make sure that the assembly containing this type is loaded.

Unable to find type [TOKEN_INFORMATION_CLASS]: make sure that the assembly containing this type is loaded.

Unable to find type [ProcessAccessFlags]: make sure that the assembly containing this type is loaded.

BTW, I have posted the full error log @ https://docs.google.com/document/d/18boeWSbvlLwpoIAMTJAp0ooNaLxe6kniYrJr_q3ZNMQ/edit?usp=sharing

' src=

Just a question, how can I grant the SESecurityPrivilege to the Set-Acl process ? If I do a whoami /priv I can see my useraccount (PS –> run as administrator) I can see the privilege is enabled, but when I try to run the script I have I get the following error :

Set-Acl : The process does not possess the ‘SeSecurityPrivilege’ privilege which is required for this operation. At C:\Scripts\SESOG\ImportACLSEv2.ps1:16 char:16 + $acl | Set-Acl $path + ~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (P:\Common:String) [Set-Acl], PrivilegeNotHeldException + FullyQualifiedErrorId : System.Security.AccessControl.PrivilegeNotHeldException,Microsoft.PowerShell.Commands.SetAclCommand

The script looks like this : $par = Import-Csv -Path “c:\scripts\sesog\ImportMainCC.csv” -Delimiter “;”

foreach ( $i in $par ) { $path= $i.Path $IdentityReference= $i.IdentityReference $AccessControlType=$i.AccessControlType $InheritanceFlags= $i.InheritanceFlags $PropagationFlags=$i.PropagationFlags $FileSystemRights=$i.FileSystemRights echo $path $IdentityReference $acl = Get-Acl $path $permission = $IdentityReference, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType $accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission $acl.SetAccessRule($accessRule) $acl | Set-Acl $path }

In the import csv a path is set and exported export rights from the original location (I am doing a fileserver migration) but on each of the folders mentioned the inherentance flag has been removed.

Pingback: PowerShell Magazine » The case of potentially broken PackageManagement for Windows 10 Insiders

' src=

You are a lifesaver! I have been fretting over how to manage service account rights on remote servers – each OU has a corresponding AD security group and GPO, and doing this manually is both time-consuming and fraught with error. I can’t wait to try this out. First PoshWSUS, then this …you rock.

Leave a comment Cancel reply

Translate this blog.

  • Search for:

Recent Posts

  • Dealing with Runspacepool Variable Scope Creep in PowerShell
  • 2018 PowerShell Resolutions
  • Quick Hits: Getting the Local Computer Name
  • Recent Articles on MCPMag
  • Quick Hits: Finding all Hyperlinks in an Excel Workbook
  • Querying UDP Ports with PowerShell
  • Changing Ownership of File or Folder Using PowerShell
  • Starting,Stopping and Restarting Remote Services with PowerShell
  • Locating Mount Points Using PowerShell
  • PowerShell and WPF: Writing Data to a UI From a Different Runspace
  • Avoiding System.Object[] (or Similar Output) when using Export-Csv
  • Quick Hits: Finding Exception Types with PowerShell
  • Building a Chart Using PowerShell and Chart Controls
  • Using PowerShell Parameter Validation to Make Your Day Easier
  • Quick Hits: Ping Sweep One Liner
  • background jobs
  • Internet Explorer
  • performance
  • powerscripting
  • Regular Expressions
  • scripting games 2012
  • scripting games 2013
  • scripting guy
  • winter scriting games 2014

Email Subscription

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Email Address:

Sign me up!

  • 5,610,713 Visitors Since August 5, 2010
  • Entries feed
  • Comments feed
  • WordPress.com

' src=

  • Already have a WordPress.com account? Log in now.
  • Subscribe Subscribed
  • Copy shortlink
  • Report this content
  • View post in Reader
  • Manage subscriptions
  • Collapse this bar

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How can I get an overview of all users with a specific user right in Windows?

I need to check that only the administrators group (sid: S-1-5-32-544) has the privilege to take ownership of files or folders (SeTakeOwnershipPrivilege).

How can I get an overview of all users/groups that have this privilege?

What I already found and tried is the following command:

The output in the file looks pretty useful:

[Unicode] Unicode=yes [Privilege Rights] SeNetworkLogonRight = *S-1-5-32-544 ... SeTakeOwnershipPrivilege = *S-1-5-32-544 ... [Version] signature="$CHICAGO$" Revision=1

With this method above I would have to read the file into my Powershell script, search for the privilege and delete the file afterwards.

Is there any other method to do this in Powershell without external modules or executables?

Thanks for your supply.

  • user-accounts

dwettstein's user avatar

5 Answers 5

There is another way using the LsaEnumerateAccountsWithUserRight Win32 API function. This has to be coded in C# ( PInvoke ) in your script and the code definition would be very long and messy.

I would avoid the above and wrap the executable instead. Why reinvent the wheel?

MFT's user avatar

  • Thanks for your reply. I assume, I will have to go this way, since I cannot use other modules or executables. Nice hint with wrapping the executable. –  dwettstein Commented Sep 9, 2014 at 9:14

Not a pure PS solution, but an option none the less. :)

You could use Microsoft's AccessChk utility ( download it here ) instead of SecEdit.

Unlike SecEdit, AccessChk outputs to the stdout, so you can easily capture its output into a PS variable, and then check that variable (with no need for an intermediate file).

Something like:

Ƭᴇcʜιᴇ007's user avatar

  • Thanks for your hint. I also found this utility. Is it preinstalled on Windows Server 2008 and 2012 machines? Unfortunately, I cannot install external modules or executables. –  dwettstein Commented Sep 9, 2014 at 9:19

Shameless promotion: check out the Carbon module (I'm the creater/maintainer). It has a Get-Privilege function that will return all a principal's privileges.

splattered bits's user avatar

  • Thanks for your reply. Nice module! Unfortunately, I can only use the "standard" modules. :( –  dwettstein Commented Sep 9, 2014 at 9:08

Maybe this command will be helpful

sanyam jain's user avatar

Here's the solution:

Francis's user avatar

  • 1 Can you please add some explanations? –  Romeo Ninov Commented Apr 19, 2016 at 6:44
  • It is questioning an instance of Wmi and extracting the requested parameter from the resultant set of policies. Pretty simple and straight forward. You could also specify a remote computer with -computername –  Francis Commented Apr 20, 2016 at 19:59

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows powershell user-accounts privileges ..

  • The Overflow Blog
  • CEO Update: Building trust in AI is key to a thriving knowledge ecosystem
  • How to improve the developer experience in today’s ecommerce world
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • Why is the deletion ungrammatical in "I like the girl [who is] the prettiest in my class" but grammatical in other sentences?
  • How would I translate a question like "you do realize...?" rather than "do you realize...?" into German?
  • Trigonometric inequality
  • How is it possible for the eval to reduce after playing the best move?
  • A strange way to end a chess tournament
  • Systematic king's overthrown culture
  • Has any mass protest in the USA after 1945 successfully pressured the government to change its decision based on the protesters' demands?
  • Buying a home with a HOA
  • The Knights and Knaves Want Out
  • Is registering to vote in the US automatically counted as a vote for that party?
  • Why do you need to beat a DC of 15 to hide?
  • modify number output format
  • APT broken due to broken python libraries
  • Magic Combination lock
  • Identify if all bools in a list are the same value, and what the distinct value is if they are the same
  • Help with generating invoices from JSON data using LaTeX
  • The bridge is too short
  • How does a modern day satellite fall apart in space?
  • Should a 10/2 cable for a clothes dryer be upgraded to 10/3 during a renovation?
  • Probability of selecting three dice rolls that sum to 6 from Six rolls
  • Best statistical analysis with (very) limited samples : MLR vs GLM vs GAM vs something else?
  • How can I block localhost access from other computers on the same local network?
  • How to know if the network is configured through /etc/network/interfaces, NetworkManager, Systemd or Netplan?
  • Pre-biased transistor vs normal transistor for digital logic

powershell get user rights assignment

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

User rights assignment in Group Policy Object using powershell?

Not able to grant user rights assignment in group policy object using PowerShell Is there any way or command to add user rights in group policy?

Manual steps:

  • Open Group Policy Management
  • Navigate to the following path in the Group Policy Object
  • Select Policy
  • Right click & Edit: Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment.
  • Add/remove the necessary users.

Image of rights which needs to be assigned

Active Directory A set of directory-based technologies included in Windows Server. 6,607 questions Sign in to follow Follow

Windows Server PowerShell Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications. PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language. 5,538 questions Sign in to follow Follow

I realise this post is quite old, but there is a post that talks about a way you could do this by building up a GPO, the same way the export/import GPO works in Powershell: https://jigsolving.com/gpo-deep-dive-part-1/ Within that article, there's a bare bones example of this on Github: https://github.com/Jigsolving/powershell/blob/main/User%20Rights%20Assignment%20GPO/create-customURAGPO.ps1

It definitely works, and this is just one way it can be done. The article focuses on basically building up the raw bones of a GPO that resembles what an exported GPO looks like, and then imports it.

Give this a try.

https://learn-powershell.net/2015/06/03/managing-privileges-using-poshprivilege

Thanks @MotoX80 for sharing this module Tried this module but it didn't work as per my expectations I am looking to add user rights in group policy in group policy management of domain controller but this module gives user rights in local policy. If you have another module or command please share I also tried Set-GPPermission but it is giving user permission to edit settings, delete, modify security.

Set-GPPermission result.png

I no longer have access to an AD environment, so I am not able to test. Perhaps another forum user can provide assistance.

Have you seen this page?

https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd759177(v=ws.11)?redirectedfrom=MSDN

https://www.ntweekly.com/2020/08/07/configure-a-group-policy-with-powershell/

Yes, already seen these pages And as per https://www.microsoft.com/en-au/download/details.aspx?id=25250 this link/sheet user rights assignment don't have registry keys.

Random thoughts from a retired sysadmin....

Well it has to be stored somewhere on the DC.

https://techgenix.com/group-policy-settings-part1/

Make a change to one policy and then search the sysvol folder and see if you can find the file that contains your update. If that's a text based file (not in binary format) then you might be able to update the policy just like you would update the content of any other text file.

I assume that you have already done the "Import-Module GroupPolicy" and searched for "GP" related commands as that page described. If you haven't, then you should start there.

Hi @ArpitShivhare-6858

I've had to do something similar in the past with automatic GPO generation, and the below was the only way I could find to do so. It basically creates the GPO manually, but it should work for your purposes

To add additional fields or users to the Local User Rights Assignments, I would recommend creating the GPO manually, then taking a look at the GptTmpl.inf file to see what format, values and syntax of the fields required. From my testing it uses SIDs, not the SamAccountName value, so you will have to pull the SID for each user that you need to add

ECS.LocalGPO

Functions/get-ecslocalgpouserrightassignment.ps1.

  • Outlook – General Tab
  • Outlook – Phone Tab
  • ADUC – General Tab
  • ADUC – Address Tab
  • ADUC – Account Tab
  • ISA/TMG Scripts
  • Active Directory on Fixed Ports
  • RPC Internet Ports in Windows 2008
  • DNS High Memory Utilization Issue
  • WP – Cookies for Comments
  • PHPBB HTTP 403 Forbidden Issue
  • Shift Key and RDP Woes
  • Domain Controller crash – memory leaking process
  • Associate MP3 files to MPG123.EXE with parameters
  • Privacy Policy

powershell get user rights assignment

  • Active Directory

Powershell GPO Deep Dive – Part 1

powershell get user rights assignment

Creating a GPO in order to set User Rights Assignment completely in PowerShell: Can it be done?

This series of posts aims to share some interesting things learned about how GPOs are structured and things discovered about what backup-gpo and import-gpo routines are doing within the Powershell GPO module . The research was limited to User Rights Assignments and scripting up such a GPO – with absolutely no warranties what so ever!

Remember that changing security settings and user rights assignments can cause issues.

It turnns out that there is another way that this can be done by creating a blank GPO and creating the relevant files directly in SYSVOL in around 10 lines of code but this does feel even more dangerous / hacky to me.

Create a GPO for User Rights Assignment in Powershell

One of my colleagues asked me if we could script up an end-to-end GPO that would add in some Deny elements within the User Rights Assignments section. I immediately replied with “yeah sure, no worries” with a vague recollection that there was now a bunch of GPO commands like New-GPO that could create a GPO and command-lets that let you set registry values ( Set-GPRegistryValue ).

Some time later I discovered that actually…. NO.. No it is not possible to script up a full GPO to do what we wanted. It is possible to make a new empty GPO, Link it, add registry settings but if there is a need to add Deny Logon type elements to the Security node under User Rights Assignment, this is not currently possible.

This discovery disappointed me to say the least. What other options are available? Before moving any further let’s talk about what our given scenario was:

We would like to script up a GPO that will allow us to dynamically inject the usernames and groups that we want to be denied access to various User Rights Assignment elements in a GPO.

An image depicting the User Rights Assignment Section of an empty GPO

Of course, you could make a GPO through the GUI and then export it as a Backup using the Backup-GPO command and then save that somewhere and you could just import that GPO using Import-GPO . In our scenario, this just won’t cut it. We need to be able to inject our own account and group names – If we just blindly import, we’ll just get a bunch of stuff that may or may not be valid based on some statically exported values.

This got me thinking: what if we could Back up a GPO, get the resultant files prepared in such a way that we can replace the relevant values in the files that it creates with the user and group names of the things we want inside the GPO, and THEN run the Import-GPO command?

Before we jump down that rabbit hole, let us consider what gets created by the backup-gpo command-let in the specific scenario we are looking at.

What’s in an Empty GPO?

In order to back up a GPO, we first need a GPO to back up.  In our example, we will create a GPO called “NewGPO”

A screenshot showing the Group Policy Management Console

Looking at this GPO, we can see that it is empty. The only thing of note for us is the Unique ID (GUID) of {28AA0345-4804-4CE9-A41D-F7C89D5D5BD3}

A screenshot of an empty GPO with nothing configured except the Unique ID

We will find this policy “{28AA0345-4804-4CE9-A41D-F7C89D5D5BD3}” under sysvol. In the filesystem, it looks like this:

A screenshot showing an example GPO under SYSVOL

The first folder “Machine” is the structure for Computer related elements. The second folder “User” is for User related Policy Elements.

Since our GPO is empty, both folders will also be empty. However there is a file called “GPT.INI” in the root of this folder (note that the filename is in capital letters – strangely, capitals only when created not restored). At this point the GPT.INI contains the GPO Version (how many times the policy has been modified and saved) and displayName of the policy as shown in the console. The encoding for this file is “UTF-8” (see screenshot below as an example):

Contents of a brand new GPO's GPT.INI file

A GPO with one User Rights Assignment value set

Lets go back into our GPO and create a single element for Deny Access to this computer from the network and set it for Administrators as pictured below:

A screenshot of a GPO where Deny access to this computer from the network has been set for Administrators

If we walk the filesystem under SYSVOL as we did earlier, we will find that everything is the same, except that the “Machine” folder tree now has a subfolder \Machine\Microsoft\Windows NT\SecEdit containing a single file called GptTmpl.inf

powershell get user rights assignment

Looking at the file, we can see it is like any old school .inf file with sections in square brackets. The last section is where the actual Logon Rights are stored. In this case; we asked for Deny Access to this computer from the network to be set for administrators. The system translated that to DenyNetworkLogonRight = *S-1-5-32-544.

The system has converted our plain text request into this instruction. The SID shown here is simply a translation from the list of well known SIDs for Administrator.

What’s inside a Backup-GPO?

Let’s back up our example GPO using the Backup-GPO command in powershell:

powershell get user rights assignment

This creates a file structure within the Administrator’s temp folder. It creates a folder with a newly created random guid (referred to as the Backup ID). The original GPO’s GUID {28AA0345-4804-4CE9-A41D-F7C89D5D5BD3} is stored in the backup as “GpoID” and can be seen in  the results of the command above (and in some of the GPO’s backed up files – more on that in a moment).

The backed up GPO has been saved under the new ID Folder name of {43E048D3-ECC6-4F29-AF9D-CF464EEF4CD5}.

Be aware that there are two extra hidden XML files that get created after running a Backup-GPO command. The first file is outside the GUID folder at the folder where the command ran, The file is called Manifest.xml and is very important if you wish to import the GPO somewhere else.

A screenshot of the top level folder of a backed up GPO

The manifest.xml file is quite ugly. It is in XML, but it will probably show as one big long line of unbroken text. Here’s a version of our manifest.xml (encoding is UTF-8) with wordwrap turned on in Notepad:

powershell get user rights assignment

In short, the Manifest.xml file is used by the import-gpo routine to provide instructions on where GPOs that have been backed up can be found. It also contains information on the domain and domain controller it was backed up from. You will also find the time and the display name of the original GPO. Each GPO backed up will be found inside a <BackupInst> tag set.

As mentioned earlier, there is another hidden file. This file is in the GUID folder and called bkupinfo.xml. It looks remarkably similar to the Manifest file with one less tag. The first tag <backups> is not present – The Backups tag is only found in the manifest file and is used to encapsulate each GPO that can be found at the backed up folder location along with its associated GUID/ID pair. In our case, we only have one GPO, so the file looks almost identical (without the <Backups> tag).

powershell get user rights assignment

NOTE: For this file to be able to be imported, you must not break some tags over new lines or the import command will completely crash the powershell session; eg; The file formatted as below would cause the client to crash. You can remove the empty lines without a problem.

powershell get user rights assignment

The purpose of the SecuritGroups section is so that if you have custom user/group names inside your policy, they can be transformed if imported into a new domain. Be aware that the entire SecurityGroups section MUST be on a single unbroken line otherwise Import-GPO will crash and terminate the current powershell session.

The purpose of the GroupPolicyCoreSettings is to capture some of the basic GPO settings, Domain, original GPO GUID (stored as ID) and any machine policies that are in use. In our example, we are only using the one policy for the Security section of our GPO – {827D319E-6EAC-11D2-A4EA-00C04F79F83A}{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}. This section MUST all be on a single unbroken line otherwise Import-GPO will crash and terminate the current powershell session.

In our example, we are actually only using the Extension highlighted in blue, so we really don’t need the other extensions for import-gpo to work. In our scenario, we could safely remove the other extensions below the extension highlighted in blue. Be aware that the entire GPO Extension lines MUST be in a continuous unbroken line otherwise Import-GPO will crash and terminate the current powershell session.

Finally, we have the gpttmpl.inf file that is stored in the same subfolder location as the live GPO. The file also is identical to what was present in SYSVOL. Be aware that this file MUST be encoded as UTF-16LE (Unicode).

To build our GPO to set just our User Rights assignment, the minimum number of files is 4 (2 hidden):

Manifest.xml in the root of the folder where the backup was created (outside the GUID folder) – hidden. backup.xml inside the root of the GUID folder bkupinfo.xml inside the root of the GUID folder – hidden. GptTmpl.inf in the same subfolder structure as the oriignal real live GPO (<Guid>\DomainSysvol\GPO\Machine\microsoft\windows nt\SecEdit)

The structure looks like this:

powershell get user rights assignment

The Backup.inf file

What if I told you… we could build this all out and remove most of the values present in the backup.inf and still import fine with import-gpo ? Tune in next week for the next part in this series to learn more. I’ll put together some example template files.

In the mean time, here’s a sneak peak at the script that will be discussed: https://github.com/Jigsolving/powershell/blob/main/User%20Rights%20Assignment%20GPO/create-customURAGPO.ps1

Happy GPOing.

A full list of User Rights Assignment

The table below lists all the User Rights Assignments and their translated constant values. Each Policy setting is linked to a page over at Microsoft (***except one – there seems to be an error over there).

Notes: *You MUST specify at least Administrator for this right ** Administrators and SERVICE MUST be granted this right *** The associated description for this right is missing over at Microsoft at time of writing.

The featured photo in this post: Part of a photo by Francisco Jesús Navarro Hernández on Unsplash

RELATED ARTICLES MORE FROM AUTHOR

Cannot verify account: microsoft system center vmm setup, install rsat tools via powershell, scheduled tasks: on event triggers with variables, protecting rpc, dhcp client stuck with 5 minute lease time, leave a reply cancel reply.

Save my name, email, and website in this browser for the next time I comment.

powershell get user rights assignment

IMAGES

  1. Set and Check User Rights Assignment via Powershell

    powershell get user rights assignment

  2. Managing User Rights in Powershell

    powershell get user rights assignment

  3. User rights assignment in Group Policy Object using powershell?

    powershell get user rights assignment

  4. User rights assignment in Group Policy Object using powershell?

    powershell get user rights assignment

  5. Set and Check User Rights Assignment via Powershell

    powershell get user rights assignment

  6. Set and Check User Rights Assignment via Powershell

    powershell get user rights assignment

VIDEO

  1. Windows Powershell : Opérateurs

  2. Understanding Group Policy: User Rights Assignment Policies

  3. PowerShell Providers and PowerShell Drives

COMMENTS

  1. Set and Check User Rights Assignment via PowerShell

    Learn how to use Powershell scripts to add, remove, and check user rights assignment for local or remote computers. See examples of how to grant Logon as a Service Right for a user with the script Set-UserRights.ps1.

  2. Powershell: Export User Rights Assignment

    I'm new to PowerShell (PS). Currently I'm using windows server 2012 and I'm interested to know whether there is any way to export User Rights Assignment into a txt file. I tried . secedit /export /areas USER_RIGHTS /cfg d:\policies.txt The above should should export it. So, I get this: Current Output.

  3. Get-CsUserPolicyAssignment (MicrosoftTeamsPowerShell)

    This cmdlets returns the effective policies for a user, based on either direct policy assignment or inheritance from a group policy assignment. For a given policy type, if an effective policy is not returned, this indicates that the effective policy for the user is either the tenant global default policy (if set) or the system global default policy. This cmdlet does not currently support ...

  4. How to list windows privileges for any user

    You can call this program within a PowerShell script, concatenate the results into a text file, then filter out just the permissions you want to know about. ... it's just getting the list of principals (in SID form) to which the rights have been assigned in User Rights Assignment (see secpol.msc). Therefore, you'll usually see the SIDs for ...

  5. Display access rights on Active Directory OUs with PowerShell

    For instance, the following command finds the users who have one of the write access rights in the domain. Get-OURights("*Write*") Finding the users who have write access rights in the domain. Before you execute the command, you have to navigate to the domain's AD drive. This MSDN page

  6. Managing User Rights in Powershell

    Managing User Rights Assignments in Powershell. Windows User Rights, also known as Windows Privileges, are traditionally managed via GPO or in the simplest of cases via the server's Local Security Policy. These assignments control special permissions that are often needed by IIS applications or other application hosting on Windows Servers.

  7. command line

    What is an equivalent for ntrights.exe on Windows 10? Set and Check User Rights Assignment via Powershell You can add, remove, and check User Rights Assignment (remotely / locally) with the following Powershell scripts.

  8. Managing Privileges using PoshPrivilege

    PoshPrivilege is a module that lets you view, enable, disable, add and remove user rights on a local or remote system. It uses reflection and pinvoke to access the Windows API and requires PowerShell V5 or higher.

  9. powershell

    How can I get an overview of all users/groups that have this privilege? What I already found and tried is the following command: secedit /export /areas USER_RIGHTS /cfg output.txt The output in the file looks pretty useful: [Unicode] Unicode=yes [Privilege Rights] SeNetworkLogonRight = *S-1-5-32-544... SeTakeOwnershipPrivilege = *S-1-5-32-544 ...

  10. User Rights Assignment

    Learn how to configure user rights for logging on and accessing computer and domain resources in Windows 10 and 11. User rights include logon rights, permissions, and privileges that can be managed in Group Policy or Local Group Policy Editor.

  11. User rights assignment in Group Policy Object using powershell

    Is there any way or command to add user rights in group policy? Manual steps: Open Group Policy Management ; Navigate to the following path in the Group Policy Object ; Select Policy ; Right click & Edit: Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment. Add/remove the necessary users.

  12. windows

    As I understand this problem, you want to translate the text output produced by secedit /export /areas USER_RIGHTS /cfg d:\policies.txt command into the equivalent output "exported from gui". I borrowed the list of equivalences from the answer at this question, added a list of equivalences for each one of the terms and used they to write a Batch file that should perform such translation.

  13. Functions/Get-ECSLocalGPOUserRightAssignment.ps1 2.1.0

    Get-ECSLocalGPOUserRightAssignment will retrieve Local Group Policy Object (GPO) user right assignments. This function is useful if you're looking to audit or backup your current user right assignments to a CSV. This function utilizes the Windows builtin SecEdit.exe to export the user rights list, and then this function parses the exported file.

  14. Powershell GPO Deep Dive

    Creating a GPO in order to set User Rights Assignment completely in PowerShell: Can it be done? This series of posts aims to share some interesting things learned about how GPOs are structured and things discovered about what backup-gpo and import-gpo routines are doing within the Powershell GPO module.The research was limited to User Rights Assignments and scripting up such a GPO - with ...

  15. Setting user rights assignment of local security policy using

    I want to edit security settings of user rights assignment of local security policy using powershell or cmd. Eg: policy = "change the system time" default_security_settings = "local service,Administrators" i want to remove everything except Administrators i have tried ntrights command, but seems like not working Any command will be appreciated

  16. Understanding Group Policies: User Rights Assignment Policies

    Learn how to manage user rights in Group Policy, such as logon rights and permissions, to control access to computer and domain resources. Watch a video or read the documentation on User Rights Assignment policies.

  17. SCOM-Scripts-and-SQL/Powershell/General Functions/Get ...

    Specifies the usernames to filter the results. Use this parameter to retrieve user rights assignments for specific users. Provide the username in the format: domain\Username. If omitted, all user rights assignments will be retrieved.

  18. Using powershell, how do I grant "Log on as service" to an account?

    <# .Synopsis Add and Remove User Right(s) for defined user(s) and computer(s). .DESCRIPTION Add and Remove User Rights via Powershell. .PARAMETER AddRight You want to Add a user right. .Parameter ComputerName Defines the name of the computer where the user right should be granted.