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!!
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment