Home
> Active Directory, Batch File, Programming > Batch file to check if user is a member of an Active Directory Group
Batch file to check if user is a member of an Active Directory Group
Due to a limitation of our software deployment software, I was asked if it was possible to copy a file based on an Active Directory group membership. After a bit of research I decided the best course of action was to utilise the DSquery and DSget commands that are part of the Windows 7 operating system.
Let’s examine the core of the script below.
- Firstly, we specify the distinguishedName of the group that we want to check and put it into a variable – we’ll use this later in our code.
- We then use “dsquery user -samid %username%” to obtained the distinguishedName of the currently logged in user by using the %username% environment variable, which is the SAMid (sAMAccountName) in Active Directory.
- We pipe the result into “dsget user -memberof -expand”. This generates a list of distinguishedNames of all the group that the user is a member of. The “-expand” parameter ensures that all nested groups are listed as well.
- We then pipe the result of this into the FindStr utility and search for the group name the we specified at the start of the process. We perform a case insensitive search and also redirect STDOUT and STDERR to NULL to stop anything being shown on the screen.
- Finally, we check the %ERRORLEVEL% value to determine if the string has been found or not.
And here’s the script:
@ECHO OFF set group="CN=Network Team - ICT Services,OU=Test,DC=domain,DC=net" dsquery user -samid %username% | dsget user -memberof -expand | findstr /i /c:%group% 1>NUL 2>NUL If %ERRORLEVEL% EQU 1 echo Not found group!! If %ERRORLEVEL% EQU 0 echo Found group!!
Categories: Active Directory, Batch File, Programming
Tags: AD Group Membership, bat
Comments (0)
Trackbacks (0)
Leave a comment
Trackback
Recent Posts
- PowerShell – Quick way to iterate through a list of items (Part II)
- Config Manager 1806 – OSD with full disk encryption not working correctly
- Windows 10 (1607) shows OneDrive in the Explorer navigation pane
- Restoring OneDrive for Business from a user who has been deleted
- Get User Principal Name – Part II
- Exchange – Get all active Out Of Office responses
- PowerShell – Get User Principal Name (One-liner)
- PowerShell – Quick way to iterate through a list of items
- Batch file to check if user is a member of an Active Directory Group
- Batch File ISO 8601 Date Format – Version 2.0