Checking AD Group Membership from a Batch File

Batch files are not dead. They are not extinct by VBScript or PowerShell. Not yet. Perhaps never. Get over it.

Here’s how to check if a user is member of a given Active Directory group and act upon the result. The principle is straightforward:

1. Parse the output of net user to retrieve the user’s AD groups
2. Use for and find to count the occurrence of a given group
3. A counter > 0 implies membership


@echo off
set i=0
set group=SomeAdGroup
set user=%username%
echo Checking if %user% is member of %group%...
for /f %%f in ('"net user %user% /domain | findstr /i %group%"') do set /a i=%i%+1
if %i% gtr 0 (goto :member)
echo %user% is not member of %group%
goto :end
echo %user% is member of %group%

Caveats! The above example is not bulletproof:

1. False positives occur when there are groups which contain part of the name of another group – e.g. checking membership of an AD group “ITDep” will return true even if the user is not a member of that specific group but (s)he is member of a group called “ITDepartement”.
2. The net user command has a problem with lengthy group names and truncates values in its output.


Finding the Closest Domain Controller

The site topology in Active Directory is what determines the “closest” domain controller. The DC used to authenticate with, is available in the %logonserver% environment variable after a successful logon.

In some scenarios you might want to know the closest DC in advance. One example is the phase of joining a new machine in AD during an automated workstation (OS) deployment. You’ll probably want to construct an LDAP path (containing the destination OU for the workstation) including the closest DC to speed up the process.

Bye bye IADsTools.dll

On Windows XP, DsGetDcName() exposed by IADsTools.dll could be used to retrieve the closest DC. (Un)fortunately, it is no longer supported since Windows Vista/2008.


On a Windows Vista/7 box with the ActiveDirectory module for PowerShell available (which comes with the Remote Server Administration Tools pack), the process of querying the closest DC is straightforward: simply use the Get-ADDomainController cmdlet. Example:

PS C:\> Import-Module ActiveDirectory
PS C:\> $dc = Get-ADDomainController -DomainName yourdomain.local -Discover -NextClosestSite
PS C:\> $dc.Name


If RSAT is not available, you’ll have to rely on functionality exposed by the .NET framework in the System.DirectoryServices namespace. It takes a little more work to achieve the same result:

PS C:\> $type = [System.DirectoryServices.ActiveDirectory.DirectoryContextType]"Domain"
PS C:\> $context = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($type, "yourdomain.local", "domainuser", "password")
PS C:\> $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)
PS C:\> $domain.FindDomainController().Name

%d bloggers like this: