JSI Tip 9781. How can I set a users country in Active Directory based upon their email address?

Using AdFind freeware and AdMod freeware, I have scripted CountryCode.bat as a sample to set the countrycode and c attributes for a user based upon the suffix of their email address. Specifically, I was asked to make a .COM suffix set c to US and countrycode to 840, and a .CA suffix to set c to CA and countrycode to 124.

NOTE: See the ISO Code and ISO Short columns.

The syntax for running CountryCode.bat is:

CountryCode \[domain\]

where domain is optional. If not specified, domain defaults to the %USERDNSDOMAIN% variable, like JSIINC.COM.

CountryCode.bat contains:

@echo off
set domain=%1
set domain=%domain:"=%
if \{%1\}==\{\} set domain=%USERDNSDOMAIN%
for /f "Skip=3 Tokens=1* Delims=:" %%a in ('adfind -default -noctl -f "&(objectcategory=person)(objectClass=user)" mail') do (
 set p1=%%a
 set p1=!p1:~1!
 set p2="%%b"
 set p2=!p2:" ="!
 if "!p1!" EQU "n" call :update 
 if !p2! EQU "" call :update
 if "!p1!" EQU "mail" set mail=!p2!
goto :EOF
if not defined dn goto :update2
if not defined mail goto update2
set work=!mail:*@[email protected]!
set work=%work:"=%
set cc=
for /f "Tokens=1-8 Delims=." %%i in ('@echo %work%') do (
 if not defined cc if "%%p" NEQ "" set cc=%%p
 if not defined cc if "%%o" NEQ "" set cc=%%o
 if not defined cc if "%%n" NEQ "" set cc=%%n
 if not defined cc if "%%m" NEQ "" set cc=%%m
 if not defined cc if "%%l" NEQ "" set cc=%%l
 if not defined cc if "%%k" NEQ "" set cc=%%k
 if not defined cc if "%%j" NEQ "" set cc=%%j
 if not defined cc if "%%i" NEQ "" set cc=%%i
if not defined cc goto update1
set mail=!mail:"=!
set cc=%cc:"=%
if /i "%cc%" EQU "CA" set c=CA&set countrycode=124&goto update1
if /i "%cc%" EQU "COM" set c=US&set countrycode=840&goto update1
goto update2
@echo admod -b %dn% "c::!c!" "countrycode::%countrycode%"
call :quiet>nul 2>&1
set dn=!p2!
set mail=
goto :EOF
admod -b %dn% "c::!c!" "countrycode::%countrycode%"

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.