active directory cheatsheet

Active Directory Cheat Sheet

This page contains my Active Directory Cheat Sheet. A list of collected one liners and vb scripts. Enjoy and feel free to add some yourself via comments!

Active Directory One Liners

List all Domain Controllers and Their IP Addresses

for /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do psexec \\%i ipconfig /all

How to Reset Active Directory User’s Password from Command Line

In this case you would need to be on the domain controller to run this:

DSQUERY USER -samid enter_username_here | dsmod user -pwd enter_new_pw_here -mustchpwd no

Remotely Reset Active Directory User’s password from command line

Requirements

  • You must have admin rights to domain controller
  • psexec
psexec domain_controller_ip DSQUERY USER -samid enter_username_here | dsmod user -pwd enter_new_pw_here -mustchpwd no enter_new_pw_here

Return the distinguished name for all users in an active directory domain

To return the distinguished name for all users in an active directory domain create a new file called getdn.bat

Content:

del c:\activeUsers.txt
DSQUERY.exe * -limit 0 -filter "(&(objectCategory=Person)(objectClass=User)(!userAccountControl:1.2.840.113556.1.4.803:=2))" >"c:\activeUsers.txt"
C:\WINDOWS\NOTEPAD.EXE c:\activeUsers.txt

List all users in security group

dsquery group -name "" | dsget group -members -expand | dsget user -fn -ln -disabled

Export all usernames and email addresses

dsquery.exe * -limit 0 -filter "(&(objectCategory=person)(objectClass=user)(mail=*))" -attr sAMAccountName name mail >"c:\PrimaryEmailAddresses.txt"
notepad "c:\PrimaryEmailAddresses.txt"

sync time domain controller

w32tm /resync

FSMO Roles

netdom query fsmo
netdom query trust
netdom query dc
ntdsutilroles Connections "Connect to server %logonserver%" Quit "selectOperation Target" "List roles for conn server" Quit Quit Quit

Global Catalog

dsquery server -isgc

Domain Controllers

netdom query dc
Nltest /dclist:%userdnsdomain%

Domain Controller IP Configuration

for /f %i in ('dsquery server -domain %userdnsdomain% -o rdn') do psexec \\%i ipconfig /all

Stale computer accounts

dsquery computer domainroot -stalepwd 180 -limit 0

Stale user accounts

dsquery user domainroot -stalepwd 180 -limit 0

Disabled user accounts

dsquery user domainroot -disabled -limit 0

AD Database disk usage

for /f %i in (‘dsquery server -domain %userdnsdomain% -o rdn’) do dir \\%i\admin$\ntds

Global Catalog Servers from DNS

dnscmd %logonserver% /enumrecords %userdnsdomain% _tcp | find /i "3268"

Global Catalog Servers from AD

dsquery * "CN=Configuration,DC=forestRootDomain" -filter "(&(objectCategory=nTDSDSA)(options:1.2.840.113556.1.4.803:=1))"

Users with no logon script

dsquery * domainroot -filter"(&(objectCategory=Person)(objectClass=User)(!scriptPath=*))"-limit 0 -attr sAMAccountName sn givenName pwdLastSet distinguishedName

User accounts with no pwd required

dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=32))"

User accounts with no pwd expiry

dsquery * domainroot -filter"(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=65536))"

User accounts that are disabled

dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(userAccountControl:1.2.840.113556.1.4.803:=2))"

DNS Information

for /f %i in (‘dsquery server -domain %userdnsdomain% -o rdn’) do dnscmd %i /info

DNS Zone Detailed information

dnscmd /zoneinfo %userdnsdomain%

Garbage Collection and tombstone

dsquery * "cn=Directory Service,cn=WindowsNT,cn=Services,cn=Configuration,DC=forestRootDomain" -attrgarbageCollPeriod tombstoneLifetime

Netsh authorised DHCP Servers

netsh dhcp show server

DSQuery authorised DHCP Servers

Dsquery * "cn=NetServices,cn=Services,cn=Configuration, DC=forestRootDomain" -attr dhcpServers

DHCP server information

netsh dhcp server \\DHCP_SERVER show all

DHCP server dump

netsh dhcp server \\DHCP_SERVER dump

WINS serer information

Netsh wins server \\WINS_SERVER dump

Group Policy Verification Tool

gpotool.exe /checkacl /verbose

AD OU membership

dsquery computer -limit 0

AD OU membership

dsquery user -limit 0

List Service Principal Names

for /f %i in (‘dsquery server -domain %userdnsdomain% -o rdn’) do setspn -L %i

Compare DC Replica Object Count

dsastat ?s:DC1;DC2;… ?b:Domain ?gcattrs:objectclass ?p:999

Check AD ACLs

acldiag dc=domainTree

NTFRS Replica Sets

for /f %i in (‘dsquery server -domain %userdnsdomain% -o rdn’) do ntfrsutl sets %i

NTFRS DS View

for /f %i in (‘dsquery server -domain %userdnsdomain% -o rdn’) do ntfrsutl ds %i

Domain Controllers per site

Dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -filter (objectCategory=Server)

DNS Zones in AD

for /f %i in (‘dsquery server -o rdn’) do Dsquery * -s %i domainroot -filter (objectCategory=dnsZone)

Enumerate DNS Server Zones

for /f %i in (‘dsquery server -o rdn’) do dnscmd %i /enumzones

Subnet information

Dsquery subnet ?limit 0

List Organisational Units

Dsquery OU

ACL on all OUs

For /f "delims=|" %i in (‘dsquery OU’) do acldiag %i

Domain Trusts

nltest /domain_trusts /v

Print DNS Zones

dnscmd DNSServer /zoneprint DNSZone

Active DHCP leases

For /f %i in (DHCPServers.txt) do for /f "delims=- " %j in (‘"netshdhcp server \\%i show scope | find /i "active""’) do netsh dhcp server\\%i scope %j show clientsv5

DHCP Server Active Scope Info

For /f %i in (DHCPServers.txt) do netsh dhcp server \\%i show scope | find /i "active"

Resolve DHCP clients hostnames

for /f "tokens=1,2,3 delims=," %i in (Output from ‘Find Subnets fromDHCP clients’) do @for /f "tokens=2 delims=: " %m in (‘"nslookup %j |find /i "Name:""’) do echo %m,%j,%k,%i

Find two online PCs per subnet

Echo. > TwoClientsPerSubnet.txt & for /f "tokens=1,2,3,4delims=, " %i in (‘"find /i "pc" ‘Output from Resolve DHCP clientshostnames’"’) do for /f "tokens=3 skip=1 delims=: " %m in (‘"Find /i /c"%l" TwoClientsPerSubnet.txt"’) do If %m LEQ 1 for /f %p in (‘"ping -n1 %i | find /i /c "(0% loss""’) do If %p==1 Echo %i,%j,%k,%l

AD Subnet and Site Information

dsquery * "CN=Subnets,CN=Sites,CN=Configuration,DC=forestRootDomain" -attr cn siteObject description location

AD Site Information

dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -attr cn description location -filter (objectClass=site)

Printer Queue Objects in AD

dsquery * domainroot -filter "(objectCategory=printQueue)" -limit 0

Group Membership with user details

dsget group "groupDN" -members | dsget user -samid -fn -mi -ln -display -empid -desc -office -tel -email -title -dept -mgr

Total DHCP Scopes

find /i "subnet" "Output from DHCP server information" | find /i "subnet"

Site Links and Cost

dsquery * "CN=Sites,CN=Configuration,DC=forestRootDomain" -attr cn costdescription replInterval siteList -filter (objectClass=siteLink)

Time gpresult

timethis gpresult /v

Check time against Domain

w32tm /monitor /computers:ForestRootPDC

Domain Controller Diagnostics

dcdiag /s:%logonserver% /v /e /c

Domain Replication Bridgeheads

repadmin /bridgeheads

Replication Failures from KCC

repadmin /failcache

Inter-site Topology servers per site

Repadmin /istg * /verbose

Replication latency

repadmin /latency /verbose

Queued replication requests

repadmin /queue *

Show connections for a DC

repadmin /showconn *

Replication summary

Repadmin /replsummary

Show replication partners

repadmin /showrepl * /all

All DCs in the forest

repadmin /viewlist *

ISTG from AD attributes

dsquery * "CN=NTDS Site Settings,CN=siteName,CN=Sites,CN=Configuration,DC=forestRootDomain" -attr interSiteTopologyGenerator

Return the object if KCC Intra/Inter site is disabled for each site

Dsquery site | dsquery * -attr * -filter "(|(Options:1.2.840.113556.1.4.803:=1)(Options:1.2.840.113556.1.4.803:=16))"

Find all connection objects

dsquery * forestRoot -filter (objectCategory=nTDSConnection) ?attr distinguishedName fromServer whenCreated displayName

Find all connection schedules

adfind -b "cn=Configuration,dc=qraps,dc=com,dc=au" -f "objectcategory=ntdsConnection" cn Schedule -csv

Software Information for each server

for /f %i in (Output from ‘Domain Controllers’) do psinfo \\%i &filever \\%i\admin$\explorer.exe \\%i\admin$\system32\vbscript.dll\\%i\admin$\system32\kernel32.dll \\%i\admin$\system32\wbem\winmgmt.exe\\%i\admin$\system32\oleaut32.dll

Check Terminal Services Delete Temp on Exit flag

For /f %i in (Output from ‘Domain Controllers’) do Reg query"\\%i\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer" /v DeleteTempDirsOnExit

For each XP workstation, query the current site and what Group Policy info

@dsquery * domainroot -filter"(&(objectCategory=Computer)(operatingSystem=Windows XPProfessional))" -limit 0 -attr cn > Workstations.txt & @For /f%i in (Workstations.txt) do @ping %i -n 1 >NUL & @if ErrorLevel0 If NOT ErrorLevel 1 @Echo %i & for /f "tokens=3" %k in (‘"regquery "\\%i\hklm\software\microsoft\windows\currentversion\grouppolicy\history" /v DCName | Find /i "DCName""’) do @for /f %m in(‘"nltest /server:%i /dsgetsite | find /i /v "completedsuccessfully""’) do @echo %i,%k,%m

Information on existing GPOs

dsquery * "CN=Policies,CN=System,domainRoot" -filter"(objectCategory=groupPolicyContainer)" -attr displayName cnwhenCreated gPCFileSysPath

Copy all Group Policy .pol files

for /f "tokens=1-8 delims=\" %i in (‘dir /b /s\\%userdnsdomain%\sysvol\%userdnsdomain%\policies\*.pol’) do @echo copy\\%i\%j\%k\%l\%m\%n\%o %m_%n.pol

Domain Controller Netlogon entries

for /f %i in (‘dsquery server /o rdn’) do echo %i & reg query\\%i\hklm\system\currentcontrolset\services\netlogon\parameters

WINS Statistics

for /f "tokens=1,2 delims=," %i in (WINSServers.txt) do netsh wins server \\%i show statistics

WINS Record counts per server

for /f "tokens=1,2 delims=," %i in (WINSServers.txt) do netsh wins server \\%i show reccount %i

WINS Server Information

for /f "tokens=2 delims=," %i in (WINSServers.txt) do netsh wins server \\%i show info

WINS Server Dump

for /f "tokens=2 delims=," %i in (WINSServers.txt) do netsh wins server \\%i dump

WINS Static Records per Server

netsh wins server \\LocalWINSServer show database servers={} rectype=1

Find policy display name given the GUID

dsquery * "CN=Policies,CN=System,DC=domainRoot" -filter (objectCategory=groupPolicyContainer) -attr Name displayName

Find empty groups

dsquery * -filter "&(objectCategory=group)(!member=*)" -limit 0-attr whenCreated whenChanged groupType sAMAccountNamedistinguishedName memberOf

Find remote NIC bandwidth

wmic /node:%server% path Win32_PerfRawData_Tcpip_NetworkInterface GET Name,CurrentBandwidth

Find remote free physical memory

wmic /node:%Computer% path Win32_OperatingSystem GET FreePhysicalMemory

Find remote system information

SystemInfo /s %Computer%

Disk statistics, including the number of files on the filesystem

chkdsk /i /c

Query IIS web sites

iisweb /s %Server% /query "Default Web Site"

Check port state and connectivity

portqry -n %server% -e %endpoint% -v

Forest/Domain Functional Levels

ldifde -d cn=partitions,cn=configuration,dc=%domain% -r"(|(systemFlags=3)(systemFlags=-2147483648))" -lmsds-behavior-version,dnsroot,ntmixeddomain,NetBIOSName -p subtree -fcon

Forest/Domain Functional Levels

dsquery * cn=partitions,cn=configuration,dc=%domain% -filter"(|(systemFlags=3)(systemFlags=-2147483648))" -attrmsDS-Behavior-Version Name dnsroot ntmixeddomain NetBIOSName

Find the parent of a process

wmic path Win32_Process WHERE Name=’notepad.exe’ GET Name,ParentProcessId

Lookup SRV records from DNS

nslookup -type=srv _ldap._tcp.dc._msdcs.{domainRoot}

Find when the AD was installed

dsquery * cn=configuration,DC=forestRootDomain -attr whencreated -scope base

Enumerate the trusts from the specified domain

dsquery * "CN=System,DC=domainRoot" -filter "(objectClass=trustedDomain)" -attr trustPartner flatName

Find a DC for each trusted domain

for /f "skip=1" %i in (‘"dsquery * CN=System,DC=domainRoot -filter(objectClass=trustedDomain) -attr trustPartner"’) do nltest /dsgetdc:%i

Check the notification packages installed on all DCs

for /f %i in (‘dsquery server /o rdn’) do @for /f "tokens=4" %m in(‘"reg query\\%i\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v"Notification Packages" | find /i "Notification""’) do @echo %i,%m

List ACLs in SDDL format

setacl -on %filepath% -ot file -actn list -lst f:sddl

Find out if a user account is currently enabled or disabled

dsquery user DC=%userdnsdomain:.=,DC=% -name %username% | dsget user -disabled -dn

Find servers in the domain

dsquery * domainroot -filter "(&(objectCategory=Computer)(objectClass=Computer)(operatingSystem=*Server*))" -limit 0

Open DS query window

rundll32 dsquery,OpenQueryWindow

VBScripts to manage Active Directory Users

Export All users from OU
Appending a Multi-Valued Attribute
Appending a Phone Number
Adding a Route to the Dial-In Properties of a User Account
Adding a User to Two Security Groups
Appending Address Page Information for a User Account
Appending a Home Phone Number to a User Account
Assigning a Published Certificate to a User Account
Changing User Account Attributes
Changing a User Password
Clearing Address Page Information for a User Account
Clearing All Published Certificates from a User Account
Clearing Department and Direct Report Information from a User Account
Clearing Telephone Attributes
Clearing Telephone Properties for a User Account
Clearing User Account Address Attributes
Clearing User Account Attributes
Configuring Account Page Information for a User Account
Configuring Address Page Information for a User Account
Configuring COM+ Information for a User Account
Configuring Dial-In Properties for a User Account
Configuring the Expiration Date for a User Account
Configuring Organization Properties for a User Account
Copying a Published Certificate to a User Account
Configuring the UPN Suffixes Defined in the Forest
Configuring User Account Telephone Numbers
Configuring User Profile Properties
Configuring User Profile Properties for a User Account
Configuring User Telephone Properties
Copying Allowed Logon Hours from One Account to Another
Creating 1,000 User Accounts
Creating an Active Directory User Account
Creating a Contact in Active Directory
Creating a User, a Group, and an OU
Deleting a Calling Station ID from a User Account
Deleting One Telephone Number from a User Account
Deleting a Phone Number
Deleting a Post Office Box from a User Account
Deleting Published Certificates from a User Account
Deleting Single- and Multi-Valued Attributes
Deleting a User Account from Active Directory
Determining When an Account Expires
Determining the Owner of a User Account
Determining When a Password Expires
Determining When a Password was Last Set
Determining User Account Status
Determining When a User Account Expires
Determining User Logon Hours
Disabling a Password Flag
Disabling the Smartcard Required Attribute for a User Account
Disabling a User Account
Disabling the User Cannot Change Password Option
Displaying Allowed Logon Hours for a User Account
Displaying Domain Password Attributes
Displaying Password Property Attributes
Displaying User Account Password Attributes
Enabling a User Account
Ensuring that an Account will not Expire
Modifying User Profile Paths
Moving a User Account
Moving a User Account to a New Domain
Preventing a User From Changing His or Her Password
Requiring a Password Change
Requiring a User to Logon on Using a Smartcard
Retrieving Organization Information
Retrieving User Account Account Properties
Retrieving User Profile Properties
Setting an Account Expiration Date
Setting a Password So It Never Expires
Setting the Primary Group for a User
Setting a Users Password
Unlocking an Active Directory User Account
Writing User Account Properties


Export all users from OU

Dim ObjWb
Dim zz
Set objRoot = GetObject("LDAP://RootDSE")
strDNC = objRoot.Get("DefaultNamingContext")
Set objDomain = GetObject("LDAP://" & strDNC) ' Bind to the top of the Domain using LDAP using ROotDSE
Set objFSO = CreateObject("Scripting.FileSystemObject")
set Fso = objFSO.OpenTextFile("output.txt", 2, True)
Fso.WriteLine("SamAccountName,CN,FirstName,LastName,Initials,Descrip,Office,Telephone,Email,WebPage,Addr1,City,State,ZipCode,Title,Department,Company,Manager,Profile,LoginScript,HomeDirectory,HomeDrive,Adspath,LastLogin,Primary SMTP")
Call enummembers(objDomain)
Sub enumMembers(objDomain)
On Error Resume Next
For Each objMember In objDomain ' go through the collection

If ObjMember.Class = "user" Then ' if not User object, move on.

ClassName = objMember.Class
SamAccountName = ObjMember.samAccountName
Cn = ObjMember.CN
FirstName = objMember.GivenName
LastName = objMember.sn
initials = objMember.initials
Descrip = objMember.description
Office = objMember.physicalDeliveryOfficeName
Telephone = objMember.telephonenumber
EmailAddr = objMember.mail
WebPage = objMember.wwwHomePage
Addr1 = objMember.streetAddress
City = objMember.l
State = objMember.st
ZipCode = objMember.postalCode
Title = ObjMember.Title
Department = objMember.Department
Company = objMember.Company
Manager = ObjMember.Manager
Profile = objMember.profilePath
LoginScript = objMember.scriptpath
HomeDirectory = ObjMember.HomeDirectory
HomeDrive = ObjMember.homeDrive
AdsPath = Objmember.Adspath
LastLogin = objMember.LastLogin

Fso.WriteLine(ClassName & "," & SamAccountName & "," & CN & "," & FirstName & "," & LastName & "," & Initials & "," & Descrip & "," & Office & "," & Telephone & "," & EmailAddr & "," & WebPage & "," & Addr1 & "," & City & "," & State & "," & ZipCode & "," & Title & "," & Department & "," & Company & "," & Manager & "," & Profile & "," & LoginScript & "," & HomeDirectory & "," & HomeDrive & "," & Adspath & "," & LastLogin & "," & Primary)

' Blank out Variables in case the next object doesn't have a value for the property
SamAccountName = "-"
Cn = "-"
FirstName = "-"
LastName = "-"
initials = "-"
Descrip = "-"
Office = "-"
Telephone = "-"
EmailAddr = "-"
WebPage = "-"
Addr1 = "-"
City = "-"
State = "-"
ZipCode = "-"
Title = "-"
Department = "-"
Company = "-"
Manager = "-"
Profile = "-"
LoginScript = "-"
HomeDirectory = "-"
HomeDrive = "-"
Primary = "-"
For ll = 1 To 20
Secondary(ll) = ""
Next
End If

' If the AD enumeration runs into an OU object, call the Sub again to itinerate

If objMember.Class = "organizationalUnit" or OBjMember.Class = "container" Then
enumMembers (objMember)
End If
Next
End Sub

MsgBox "Done" ' show that script is complete

Appending a Multi-Valued Attribute

Adds an additional URL to a user account. Demonstrates how to append a new value to a multi-valued attribute.

Const ADS_PROPERTY_APPEND = 3 

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_APPEND, _
  "url", Array("http://www.fabrikam.com/policy")

objUser.SetInfo

Appending a Phone Number

Appends an additional home phone number for a user.

Const ADS_PROPERTY_APPEND = 3 

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_APPEND, _
  "otherHomePhone", Array("(425) 555-1113")

objUser.SetInfo

Adding a Route to the Dial-In Properties of a User Account

Appends a new route to the Dial-In properties of a user account in Active Directory. This operation adds the new route without deleting any existing routes.

Const ADS_PROPERTY_APPEND = 3 

Set objUser = GetObject _
   ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_APPEND, _
    "msRASSavedFramedRoute", _
        Array("128.168.0.0/15 0.0.0.0 5")
objUser.PutEx ADS_PROPERTY_APPEND, _
    "msRADIUSFramedRoute", _
        Array("128.168.0.0/15 0.0.0.0 5")
objUser.SetInfo

Adding a User to Two Security Groups

Adds a user (MyerKen) to two different Active Directory security groups: Atl-Users and NA-Employees.

Const ADS_PROPERTY_APPEND = 3

Set objGroup = GetObject _
    ("LDAP://cn=Atl-Users,cn=Users,dc=NA,dc=fabrikam,dc=com")
objGroup.PutEx ADS_PROPERTY_APPEND, _
    "member", Array("cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objGroup.SetInfo

Set objGroup = GetObject _
    ("LDAP://cn=NA-Employees,cn=Users,dc=NA,dc=fabrikam,dc=com")
objGroup.PutEx ADS_PROPERTY_APPEND, _
    "member", Array("cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objGroup.SetInfo

Appending Address Page Information for a User Account

Appends new entries to the postOfficeBox attribute of an Active Directory user account. This operation adds the new post office boxes without deleting any existing entries.

Const ADS_PROPERTY_APPEND = 3 

Set objUser = GetObject _
   ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_APPEND, "postOfficeBox", Array("2225","2226")
objUser.SetInfo

Appending a Home Phone Number to a User Account

Appends a new phone number to the otherHomePhone attribute of an Active Directory user account. This operation adds the phone number to the attribute without deleting ant existing phone numbers.

Const ADS_PROPERTY_APPEND = 3 

Set objUser = GetObject _
   ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_APPEND, "otherHomePhone", Array("(425) 555-0116")
objUser.SetInfo

Assigning a Published Certificate to a User Account

Copies a published certificate from a template account (userTemplate) and assigns it to the MyerKen Active Directory user account. This operation replaces any existing published certificates for the MyerKen account.

On Error Resume Next
Const ADS_PROPERTY_UPDATE = 2 

Set objUserTemplate = _
    GetObject("LDAP://cn=userTemplate,OU=Management,dc=NA,dc=fabrikam,dc=com")
arrUserCertificates = objUserTemplate.GetEx("userCertificate")

Set objUser = _
    GetObject("LDAP://cn=MyerKen,OU=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_UPDATE, "userCertificate", arrUserCertificates
objUser.SetInfo

Changing User Account Attributes

Configures user account attributes found on the General Properties page of the user account object in Active Directory users and Computers.

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.Put "givenName", "Ken"
objUser.Put "initials", "E."
objUser.Put "sn", "Myer"
objUser.Put "displayName", "Myer, Ken"
objUser.Put "physicalDeliveryOfficeName", "Room 4358"
objUser.Put "telephoneNumber", "(425) 555-1211"
objUser.Put "mail", "myerken@fabrikam.com"
objUser.Put "wWWHomePage", "http://www.fabrikam.com"   

objUser.PutEx ADS_PROPERTY_UPDATE, _
    "description", Array("Management staff")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherTelephone", Array("(800) 555-1212", "(425) 555-1213")
objUser.PutEx ADS_PROPERTY_UPDATE, _
     "url", Array("http://www.fabrikam.com/management")

objUser.SetInfo

Changing a User Password

Changes the password for a user. Requires you to know the user’s previous password.

Set objUser = GetObject _
    ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.ChangePassword "i5A2sj*!", "jl3R86df"

Clearing Address Page Information for a User Account

Removes all information for the c (country) and postOfficeBox attributes of the MyerKen Active Directory user account.

Const ADS_PROPERTY_CLEAR = 1 

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_CLEAR, "c", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "postOfficeBox", 0
objUser.SetInfo

Clearing All Published Certificates from a User Account

Removes all published certificates for the MyerKen Active Directory user account.

Const ADS_PROPERTY_CLEAR = 1
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_CLEAR, "userCertificate", 0
objUser.SetInfo

Clearing Department and Direct Report Information from a User Account

Removes all information from the deparment, directReports, and manager attributes of the MyerKen Active Directory user account.

On Error Resume Next
Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D
Const ADS_PROPERTY_CLEAR = 1
Set objUser = GetObject _
   ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_CLEAR, "department", 0
objUser.SetInfo

arrDirectReports = objUser.GetEx("directReports")
If err.number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Quit
Else
    For Each strValue in arrDirectReports
        Set objUserSource = GetObject("LDAP://" & strValue)
        objUserSource.PutEx ADS_PROPERTY_CLEAR, "manager", 0
        objUserSource.SetInfo
    Next
End If

Clearing Telephone Attributes

Clears selected telephone-related attributes for a user account.

Const ADS_PROPERTY_CLEAR = 1 

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_CLEAR, "info", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "otherPager", 0

objUser.SetInfo

Clearing Telephone Properties for a User Account

Removes all information from the info and otherPager attributes of the MyerKen Active Directory user account.

Const ADS_PROPERTY_CLEAR = 1 

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_CLEAR, "info", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "otherPager", 0
objUser.SetInfo

Clearing User Account Address Attributes

Clears selected address-related attributes for a user account.

Const ADS_PROPERTY_CLEAR = 1
Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_CLEAR, "streetAddress", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "c", 0

objUser.SetInfo

Clearing User Account Attributes

Clears selected attributes for a user account.

Const ADS_PROPERTY_CLEAR = 1 

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_CLEAR, "initials", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "otherTelephone", 0

objUser.SetInfo

Configuring Account Page Information for a User Account

Configures basic account information for the MyerKen Active Directory user account.

Set objUser = GetObject _
  ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

objUser.Put "userPrincipalName", "MyerKen@fabrikam.com"
objUser.Put "sAMAccountName", "MyerKen01"
objUser.Put "userWorkstations","wks1,wks2,wks3"

objUser.SetInfo

Configuring Address Page Information for a User Account

Configures address-related information for the MyerKen Active Directory user account.

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
   ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com") 

objUser.Put "streetAddress", "Building 43" & vbCrLf & "One Microsoft Way"
objUser.Put "l", "Redmond"
objUser.Put "st", "Washington"
objUser.Put "postalCode", "98053"
objUser.Put "c", "US"

objUser.PutEx ADS_PROPERTY_UPDATE, _
 "postOfficeBox", Array("2222", "2223", "2224")

objUser.SetInfo

Configuring COM+ Information for a User Account

Sets COM+ information for the MyerKen Active Directory user account.

Set objUser = GetObject _
  ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

objUser.Put "msCOM-UserPartitionSetLink", _
  "cn=PartitionSet1,cn=ComPartitionSets,cn=System,dc=NA,dc=fabrikam,dc=com"

objUser.SetInfo

Configuring Dial-In Properties for a User Account

Configures Dial-In attribute values for the MyerKen Active Directory user account.

Const ADS_PROPERTY_UPDATE = 2

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

objUser.Put "msNPAllowDialin", TRUE
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "msNPSavedCallingStationID", Array("555-0100", "555-0111")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "msNPCallingStationID", Array("555-0100", "555-0111")
objUser.Put "msRADIUSServiceType", 4
objUser.Put "msRADIUSCallbackNumber", "555-0112"
objUser.Put "msRASSavedFramedIPAddress", 167903442
objUser.Put "msRADIUSFramedIPAddress", 167903442 'value of 10.2.0.210
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "msRASSavedFramedRoute", _
        Array("10.1.0.0/16 0.0.0.0 1", "192.168.1.0/24 0.0.0.0 3")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "msRADIUSFramedRoute", _
        Array("10.1.0.0/16 0.0.0.0 1", "192.168.1.0/24 0.0.0.0 3")

objUser.SetInfo

Configuring the Expiration Date for a User Account

Configures the MyerKen Active Directory user account to expire on March 30, 2003.

Set objUser = GetObject _
  ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.AccountExpirationDate = "03/30/2003"
objUser.SetInfo

Configuring Organization Properties for a User Account

Configures organization information for the MyerKen Active Directory user account. The script also assigns MyerKen as the manager for LewJudy and AkersKim.

Set objUser = GetObject _
    ("LDAP://cn=Myerken,ou=Management,dc=NA,dc=fabrikam,dc=com")

objUser.Put "title", "Manager"
objUser.Put "department", "Executive Management Team"
objUser.Put "company", "Fabrikam"
objUser.Put "manager", _
    "cn=AckermanPilar,OU=Management,dc=NA,dc=fabrikam,dc=com"
objUser.SetInfo

Set objUser01 = GetObject _
    ("LDAP://cn=LewJudy,OU=Sales,dc=NA,dc=fabrikam,dc=com")
Set objUser02 = GetObject _
    ("LDAP://cn=AckersKim,OU=Sales,dc=NA,dc=fabrikam,dc=com")

objUser01.Put "manager", objUser.Get("distinguishedName")
objUser02.Put "manager", objUser.Get("distinguishedName")   

objUser01.SetInfo
objUser02.SetInfo

Copying a Published Certificate to a User Account

Copies a published certificate from a template account (userTemplate) to the MyerKen Active Directory user account. This operation appends the new certificate without deleting any existing certificates.

On Error Resume Next
Const ADS_PROPERTY_APPEND = 3 

Set objUserTemplate = _
    GetObject("LDAP://cn=userTemplate,OU=Management,dc=NA,dc=fabrikam,dc=com")
arrUserCertificates = objUserTemplate.GetEx("userCertificate")

Set objUser = _
    GetObject("LDAP://cn=MyerKen,OU=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_APPEND, "userCertificate", arrUserCertificates
objUser.SetInfo

Configuring the UPN Suffixes Defined in the Forest

Configures the upnSuffixes attribute of the Partitions container and displays the new values to the operator.

Const ADS_PROPERTY_APPEND = 3
Set objPartitions = GetObject _
    ("LDAP://cn=Partitions,cn=Configuration,dc=fabrikam,dc=com")

objPartitions.PutEx ADS_PROPERTY_APPEND, _
    "upnSuffixes", Array("sa.fabrikam.com","corp.fabrikam.com")
objPartitions.SetInfo

For Each Suffix in objPartitions.GetEx("upnSuffixes")
    WScript.Echo Suffix
Next

Configuring User Account Telephone Numbers

Configures telephone numbers and calling information for the MyerKen Active Directory user account.

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com") 

objUser.Put "homePhone", "(425) 555-0100"
objUser.Put "pager", "(425) 555-0101"
objUser.Put "mobile", "(425) 555-0102"
objUser.Put "facsimileTelephoneNumber", "(425) 555-0103"
objUser.Put "ipPhone", "5555"
objUser.Put "info", "Please do not call this user account" & _
    " at home unless there is a work-related emergency. Call" & _
    " this user's mobile phone before calling the pager number."

objUser.PutEx ADS_PROPERTY_UPDATE, "otherHomePhone", Array("(425) 555-0110")
objUser.PutEx ADS_PROPERTY_UPDATE, "otherPager", Array("(425) 555-0111")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherMobile", Array("(425) 555-0112", "(425) 555-0113")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherFacsimileTelephoneNumber", Array("(425) 555-0114")
objUser.PutEx ADS_PROPERTY_UPDATE, "otherIpPhone", Array("5556")

objUser.SetInfo

Configuring User Profile Properties

Configures user profile settings for a user account.

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "profilePath", "\\sea-dc-01\Profiles\myerken"
objUser.Put "scriptPath", "logon.bat"
objUser.Put "homeDirectory", "\\sea-dc-01\HomeFolders\myerken"
objUser.Put "homeDrive", "H"

objUser.SetInfo

Configuring User Profile Properties for a User Account

Configures user profile properties for the MyerKen Active Directory user account.

Set objUser = GetObject _
    ("LDAP://cn=Myerken,ou=Management,dc=NA,dc=fabrikam,dc=com")

objUser.Put "profilePath", "\\sea-dc-01\Profiles\myerken"
objUser.Put "scriptPath", "logon.bat"
objUser.Put "homeDirectory", "\\sea-dc-01\HomeFolders\myerken"
objUser.Put "homeDrive", "H"

objUser.SetInfo

Configuring User Telephone Properties

Configures telephone numbers and telephone-related attributes for a user account.

Const ADS_PROPERTY_UPDATE = 2
Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.Put "homePhone", "(425) 555-1111"
objUser.Put "pager", "(425) 555-2222"
objUser.Put "mobile", "(425) 555-3333"
objUser.Put "facsimileTelephoneNumber", "(425) 555-4444"
objUser.Put "ipPhone", "5555"
objUser.Put "info", "Please do not call this user account" & _
  " at home unless there is a work-related emergency. Call" & _
  " this user's mobile phone before calling the pager number"

objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherHomePhone", Array("(425) 555-1112")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherPager", Array("(425) 555-2223")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherMobile", Array("(425) 555-3334", "(425) 555-3335")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherFacsimileTelephoneNumber", Array("(425) 555-4445")
objUser.PutEx ADS_PROPERTY_UPDATE, _
    "otherIpPhone", Array("6666")

objUser.SetInfo

Copying Allowed Logon Hours from One Account to Another

Copies the allowed logon hours from a template account (userTemplate) and assigns them to the MyerKen Active Directory user account. The MyerKen account will thus have the same logon hour restrictions as those assigned to the userTemplate account.

On Error Resume Next
Set objUserTemplate = _
    GetObject("LDAP://cn=userTemplate,OU=Management,dc=NA,dc=fabrikam,dc=com")
arrLogonHours = objUserTemplate.Get("logonHours")

Set objUser = _
    GetObject("LDAP://cn=MyerKen,OU=Management,dc=NA,dc=fabrikam,dc=com")
objUser.Put "logonHours", arrLogonHours
objUser.SetInfo

Creating 1,000 User Accounts

Demonstration script that creates 1,000 user accounts (named UserNo1, UserNo2, UserNo3, etc.) in the Users container in Active Directory. The script is useful for test scenarios that require multiple user accounts.

Set objRootDSE = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Users," & _
    objRootDSE.Get("defaultNamingContext"))

For i = 1 To 1000
    Set objLeaf = objContainer.Create("User", "cn=UserNo" & i)
    objLeaf.Put "sAMAccountName", "UserNo" & i
    objLeaf.SetInfo
Next

WScript.Echo "1000 Users created."

Creating an Active Directory User Account

Creates a user account in Active Directory. This script only creates the account, it does not enable it.

Set objOU = GetObject("LDAP://OU=management,dc=fabrikam,dc=com")
Set objUser = objOU.Create("User", "cn=MyerKen")
objUser.Put "sAMAccountName", "myerken"
objUser.SetInfo

Creating a Contact in Active Directory

Creates a contact account named MyerKen in the Management organizational unit in a hypothetical domain named fabrikam.com.

Creating a Contact in Active Directory

Creating a User, a Group, and an OU

Demonstration script that: 1) creates a new Active Directory organizational unit; 2) creates a new user account and new security group; and, 3) adds the new user as a member of that security group.

Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")
Set objOU = objDomain.Create("organizationalUnit", "ou=Management")
objOU.SetInfo

Set objOU = GetObject("LDAP://OU=Management,dc=fabrikam,dc=com")
Set objUser = objOU.Create("User", "cn= AckermanPilar")
objUser.Put "sAMAccountName", "AckermanPila"
objUser.SetInfo

Set objOU = GetObject("LDAP://OU=Management,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=atl-users")
objGroup.Put "sAMAccountName", "atl-users"
objGroup.SetInfo

objGroup.Add objUser.ADSPath

Deleting a Calling Station ID from a User Account

Removes a specific calling station ID from the MyerKen Active Directory user account. This operation only removes the specified calling station ID; no other IDs are deleted.

Const ADS_PROPERTY_DELETE = 4 

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_DELETE, _
    "msNPSavedCallingStationID", Array("555-0111")
objUser.PutEx ADS_PROPERTY_DELETE, _
    "msNPCallingStationID", Array("555-0111")

objUser.SetInfo

Deleting One Telephone Number from a User Account

Deletes a phone number from the otherMobile attribute of the MyerKen Active Directory user account. This operation removes only one phone number (425-555-0113) without affecting any other phone numbers.

Set objUser = GetObject _
  ("LDAP://cn=Myerken,ou=Management,dc=NA,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_DELETE, "otherMobile", Array("(425) 555-0113") 

objUser.SetInfo
objComptCopy.SetInfo

Deleting a Phone Number

Deletes a phone number from a user account with multiple mobile phone numbers.

Const ADS_PROPERTY_DELETE = 4

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_DELETE, _
  "otherMobile", Array("(425) 555-3334") 

objUser.SetInfo

Deleting a Post Office Box from a User Account

Removes a specified value (2224) from the postOfficeBox attribute of the MyerKen Active Directory user account. This operation removes only the specified post office box; other entries will not be deleted.

Const ADS_PROPERTY_DELETE = 4 

Set objUser = GetObject _
   ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_DELETE, "postOfficeBox", Array("2224")

objUser.SetInfo

Deleting Published Certificates from a User Account

Retrieves a set of published certificates from a template account (userTemplate), and then deletes each of those certificates from the MyerKen Active Directory user account.

On Error Resume Next
Const ADS_PROPERTY_DELETE = 4 

Set objUserTemplate = _
    GetObject("LDAP://cn=userTemplate,OU=Management,dc=NA,dc=fabrikam,dc=com")
arrUserCertificates = objUserTemplate.GetEx("userCertificate")

Set objUser = _
    GetObject("LDAP://cn=MyerKen,OU=Management,dc=NA,dc=fabrikam,dc=com")
objUser.PutEx ADS_PROPERTY_DELETE, "userCertificate", arrUserCertificates
objUser.SetInfo

Deleting Single- and Multi-Valued Attributes

Deletes selected attributes from a user account. Demonstrates how to delete single-valued attributes as well as how to delete a single entry from a multi-valued attribute.

Const ADS_PROPERTY_DELETE = 4

Set objUser = GetObject _
   ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com") 

objUser.PutEx ADS_PROPERTY_DELETE, _
  "otherTelephone", Array("(425) 555-1213")
objUser.PutEx ADS_PROPERTY_DELETE, _
  "initials", Array("E.")

objUser.SetInfo

Deleting a User Account from Active Directory

Deletes the user account for MyerKen from the HR organizational unit in a hypothetical domain named fabrikam.com.

Set objOU = GetObject("LDAP://ou=hr,dc=fabrikam,dc=com")
objOU.Delete "user", "cn=MyerKen"

Determining When an Account Expires

Returns the expiration date for a user account.

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

dtmAccountExpiration = objUser.AccountExpirationDate 

If err.number = -2147467259 Or _
 dtmAccountExpiration = "1/1/1970" Then
  WScript.echo "No account expiration specified"
Else
  WScript.echo "Account expiration:" & _
    objUser.AccountExpirationDate
End If

Determining the Owner of a User Account

Reports the owner of the MyerKen Active Directory user account.

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

Set objNtSecurityDescriptor = objUser.Get("ntSecurityDescriptor")
WScript.Echo "Owner Tab"
WScript.Echo "Current owner of this item: " & objNtSecurityDescriptor.Owner

Determining When a Password Expires

Determines the date when a user password will expire.

Const SEC_IN_DAY = 86400
Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000

Set objUserLDAP = GetObject _
  ("LDAP://CN=myerken,OU=management,DC=fabrikam,DC=com")
intCurrentValue = objUserLDAP.Get("userAccountControl")

If intCurrentValue and ADS_UF_DONT_EXPIRE_PASSWD Then
  wscript.echo "The password does not expire."
Else
  dtmValue = objUserLDAP.PasswordLastChanged
  Wscript.echo "The password was last changed on " & _
  DateValue(dtmValue) & " at " & TimeValue(dtmValue) & VbCrLf & _
  "The difference between when the password was last set" & VbCrLf & _
  "and today is " & int(now - dtmValue) & " days"
  intTimeInterval = int(now - dtmValue)

  Set objDomainNT = GetObject("WinNT://fabrikam")
  intMaxPwdAge = objDomainNT.Get("MaxPasswordAge")
  If intMaxPwdAge < 0 Then     WScript.Echo "The Maximum Password Age is set to 0 in the " & _       "domain. Therefore, the password does not expire."   Else     intMaxPwdAge = (intMaxPwdAge/SEC_IN_DAY)     Wscript.echo "The maximum password age is " & intMaxPwdAge & " days"     If intTimeInterval >= intMaxPwdAge Then
      Wscript.echo "The password has expired."
    Else
      Wscript.echo "The password will expire on " & _
      DateValue(dtmValue + intMaxPwdAge) & " (" & _
      int((dtmValue + intMaxPwdAge) - now) & " days from today" & ")."
    End If
  End If
End If

Determining When a Password was Last Set

Identifies the last time a user password was set.

Set objUser = GetObject _
    ("LDAP://CN=myerken,OU=management,DC=Fabrikam,DC=com")
dtmValue = objUser.PasswordLastChanged
WScript.echo "pwdLastSet is: " & dtmValue

Determining User Account Status

Identifies whether a user account is enabled or disabled.

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

If objUser.AccountDisabled = FALSE Then
      WScript.Echo "The account is enabled."
Else
      WScript.Echo "The account is disabled."
End If

Determining When a User Account Expires

Reports the date that the MyerKen Active Directory user account expires.

On Error Resume Next
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
dtmAccountExpiration = objUser.AccountExpirationDate 

If Err.Number = -2147467259 Or dtmAccountExpiration = "1/1/1970" Then
    WScript.Echo "No account expiration specified"
Else
    WScript.Echo "Account expiration: " & objUser.AccountExpirationDate
End If

Determining User Logon Hours

Retrieves the allowed logon hours for a user.

Dim arrLogonHoursBytes(20)
Dim arrLogonHoursBits(167)
arrDayOfWeek = Array _
  ("Sun", "Mon", "Tue", "Wed", _
   "Thu", "Fri", "Sat")

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfoEx Array("logonHours"), 0
arrLogonHours = objUser.Get("logonHours")

For i = 1 To LenB(arrLogonHours)
     arrLogonHoursBytes(i-1) = AscB(MidB(arrLogonHours, i, 1))
Next

intCounter = 0
intLoopCounter = 0
WScript.Echo "Day  Byte 1   Byte 2   Byte 3"
For Each LogonHourByte In arrLogonHoursBytes
  arrLogonHourBits = GetLogonHourBits(LogonHourByte)

   If intCounter = 0 Then
    WScript.STDOUT.Write arrDayOfWeek(intLoopCounter) & Space(2)
    intLoopCounter = intLoopCounter + 1
  End If

    For Each LogonHourBit In arrLogonHourBits
        WScript.STDOUT.Write LogonHourBit
        intCounter = 1 + intCounter

        If intCounter = 8 or intCounter = 16 Then
          WScript.STDOUT.Write Space(1)
        End If

        If intCounter = 24 Then
          WScript.echo VbCr
          intCounter = 0
        End If
    Next
Next

Function GetLogonHourBits(x)
    Dim arrBits(7)
    For i = 7 to 0 Step -1
        If x And 2^i Then
            arrBits(i) = 1
        Else
            arrBits(i) = 0
        End If
    Next
    GetLogonHourBits = arrBits
End Function

Disabling a Password Flag

Disables the option allowing a password to be stored using reversible encrypted text.

Const ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = &H80

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

If intUAC AND _
  ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED Then
    objUser.Put "userAccountControl", intUAC XOR _
      ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
    objUser.SetInfo
End If

Disabling the Smartcard Required Attribute for a User Account

Disables the setting that required MyerKen to use a smartcard when logging on to Active Directory.

Const ADS_UF_SMARTCARD_REQUIRED = &h40000
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

intUAC = objUser.Get("userAccountControl")

If (intUAC AND ADS_UF_SMARTCARD_REQUIRED) <> 0 Then
    objUser.Put "userAccountControl", intUAC XOR ADS_UF_SMARTCARD_REQUIRED
    objUser.SetInfo
End If

Disabling a User Account

Disables a user account.

Const ADS_UF_ACCOUNTDISABLE = 2

Set objUser = GetObject _
("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

objUser.Put "userAccountControl", intUAC OR ADS_UF_ACCOUNTDISABLE
objUser.SetInfo

Disabling the User Cannot Change Password Option

Disables the User Cannot Change Password option, allowing the user to change their password.

Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const CHANGE_PASSWORD_GUID  = _
  "{ab721a53-1e2f-11d0-9819-00aa0040529b}"

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
Set objSD   = objUser.Get("nTSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
arrTrustees = Array("nt authority\self", "everyone")

For Each strTrustee In arrTrustees
  For Each ace In objDACL
    If(LCase(ace.Trustee) = strTrustee) Then
      If((ace.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) And _
        (LCase(ace.ObjectType) = CHANGE_PASSWORD_GUID)) Then
        objDACL.RemoveAce ace
      End If
    End If
  Next
Next

objUser.Put "nTSecurityDescriptor", objSD
objUser.SetInfo

Displaying Allowed Logon Hours for a User Account

Returns the allowed logon hours for the MyerKen Active Directory user account.

On Error Resume Next
Dim arrLogonHoursBytes(20)
Dim arrLogonHoursBits(167)
arrDayOfWeek = Array _
    ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
arrLogonHours = objUser.Get("logonHours")

For i = 1 To LenB(arrLogonHours)
    arrLogonHoursBytes(i-1) = AscB(MidB(arrLogonHours, i, 1))
    WScript.Echo "MidB returns: " & MidB(arrLogonHours, i, 1)
    WScript.Echo "arrLogonHoursBytes: " & arrLogonHoursBytes(i-1)
    wscript.echo vbcrlf
Next

intCounter = 0
intLoopCounter = 0
WScript.echo "Day  Byte 1   Byte 2   Byte 3"
For Each LogonHourByte In arrLogonHoursBytes
    arrLogonHourBits = GetLogonHourBits(LogonHourByte)

    If intCounter = 0 Then
        WScript.STDOUT.Write arrDayOfWeek(intLoopCounter) & Space(2)
        intLoopCounter = intLoopCounter + 1
    End If

    For Each LogonHourBit In arrLogonHourBits
        WScript.STDOUT.Write LogonHourBit
        intCounter = 1 + intCounter

        If intCounter = 8 or intCounter = 16 Then
            Wscript.STDOUT.Write Space(1)
        End If

        If intCounter = 24 Then
            WScript.echo vbCr
            intCounter = 0
        End If
    Next
Next

Function GetLogonHourBits(x)
    Dim arrBits(7)
    For i = 7 to 0 Step -1
        If x And 2^i Then
            arrBits(i) = 1
        Else
            arrBits(i) = 0
        End If
    Next
    GetLogonHourBits = arrBits
End Function

Displaying Domain Password Attributes

Displays password policy settings for the domain.

Const MIN_IN_DAY = 1440, SEC_IN_MIN = 60

Set objDomain = GetObject("WinNT://fabrikam")
Set objAdS = GetObject("LDAP://dc=fabrikam,dc=com")

intMaxPwdAgeSeconds = objDomain.Get("MaxPasswordAge")
intMinPwdAgeSeconds = objDomain.Get("MinPasswordAge")
intLockOutObservationWindowSeconds = objDomain.Get("LockoutObservationInterval")
intLockoutDurationSeconds = objDomain.Get("AutoUnlockInterval")
intMinPwdLength = objAds.Get("minPwdLength")

intPwdHistoryLength = objAds.Get("pwdHistoryLength")
intPwdProperties = objAds.Get("pwdProperties")
intLockoutThreshold = objAds.Get("lockoutThreshold")
intMaxPwdAgeDays = _
  ((intMaxPwdAgeSeconds/SEC_IN_MIN)/MIN_IN_DAY) & " days"
intMinPwdAgeDays = _
  ((intMinPwdAgeSeconds/SEC_IN_MIN)/MIN_IN_DAY) & " days"
intLockOutObservationWindowMinutes = _
  (intLockOutObservationWindowSeconds/SEC_IN_MIN) & " minutes"

If intLockoutDurationSeconds <> -1 Then
  intLockoutDurationMinutes = _
(intLockOutDurationSeconds/SEC_IN_MIN) & " minutes"
Else
  intLockoutDurationMinutes = _
    "Administrator must manually unlock locked accounts"
End If

WScript.Echo "maxPwdAge = " & intMaxPwdAgeDays
WScript.Echo "minPwdAge = " & intMinPwdAgeDays
WScript.Echo "minPwdLength = " & intMinPwdLength
WScript.Echo "pwdHistoryLength = " & intPwdHistoryLength
WScript.Echo "pwdProperties = " & intPwdProperties
WScript.Echo "lockOutThreshold = " & intLockoutThreshold
WScript.Echo "lockOutObservationWindow = " & intLockOutObservationWindowMinutes
WScript.Echo "lockOutDuration = " & intLockoutDurationMinutes

Displaying Password Property Attributes

Displays password settings for the domain.

Set objHash = CreateObject("Scripting.Dictionary")

objHash.Add "DOMAIN_PASSWORD_COMPLEX", &h1
objHash.Add "DOMAIN_PASSWORD_NO_ANON_CHANGE", &h2
objHash.Add "DOMAIN_PASSWORD_NO_CLEAR_CHANGE", &h4
objHash.Add "DOMAIN_LOCKOUT_ADMINS", &h8
objHash.Add "DOMAIN_PASSWORD_STORE_CLEARTEXT", &h16
objHash.Add "DOMAIN_REFUSE_PASSWORD_CHANGE", &h32

Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")

intPwdProperties = objDomain.Get("PwdProperties")
WScript.Echo "pwdProperties = " & intPwdProperties

For Each Key In objHash.Keys
    If objHash(Key) And intPwdProperties Then
        WScript.Echo Key & " is enabled"
    Else
        WScript.Echo Key & " is disabled"
    End If
Next

Displaying User Account Password Attributes

Displays password-related attributes for an individual user account.

Const ADS_UF_PASSWORD_EXPIRED = &h800000
Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const CHANGE_PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}"

Set objHash = CreateObject("Scripting.Dictionary")
objHash.Add "ADS_UF_PASSWD_NOTREQD", &h00020
objHash.Add "ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED", &h0080
objHash.Add "ADS_UF_DONT_EXPIRE_PASSWD", &h10000

Set objUser = GetObject _
  ("LDAP://CN=MyerKen,OU=management,DC=Fabrikam,DC=com")
intUserAccountControl = objUser.Get("userAccountControl")

Set objUserNT = GetObject("WinNT://fabrikam/myerken")
intUserFlags = objUserNT.Get("userFlags")

If ADS_UF_PASSWORD_EXPIRED And intUserFlags Then
  blnExpiredFlag = True
  Wscript.Echo "ADS_UF_PASSWORD_EXPIRED is enabled"
Else
  Wscript.Echo "ADS_UF_PASSWORD_EXPIRED is disabled"
End If

For Each Key In objHash.Keys
  If objHash(Key) And intUserAccountControl Then
    WScript.Echo Key & " is enabled"
  Else
    WScript.Echo Key & " is disabled"
  End If
Next

Set objSD = objUser.Get("nTSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
For Each Ace In objDACL
  If ((Ace.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) And _
      (LCase(Ace.ObjectType) = CHANGE_PASSWORD_GUID)) Then
    blnACEPresent = True
  End If
Next
If blnACEPresent Then
  Wscript.Echo "ADS_UF_PASSWD_CANT_CHANGE is enabled"
Else
  Wscript.Echo "ADS_UF_PASSWD_CANT_CHANGE is disabled"
End If

If blnExpiredFlag = True Then
  Wscript.echo "pwdLastSet is null"
Else
  Wscript.echo "pwdLastSet is " & objUser.PasswordLastChanged
End If

Enabling a User Account

Enables a user account.

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.AccountDisabled = FALSE
objUser.SetInfo

Ensuring that an Account will not Expire

Configures a user account so that it will not expire. This is done by setting the expiration date to 1/1/1970.

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.AccountExpirationDate = "01/01/1970"
objUser.SetInfo

Modifying User Profile Paths

Changes the server name portion of the user profile path to \fabrikam for the MyerKen Active Directory user account.

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

strCurrentProfilePath = objUser.Get("profilePath")
intStringLen = Len(strCurrentProfilePath)
intStringRemains = intStringLen - 11
strRemains = Mid(strCurrentProfilePath, 12, intStringRemains)
strNewProfilePath = "\\fabrikam" & strRemains
objUser.Put "profilePath", strNewProfilePath
objUser.SetInfo

Moving a User Account

Moves a user account from one OU to another.

Set objOU = GetObject("LDAP://ou=sales,dc=na,dc=fabrikam,dc=com")
objOU.MoveHere _
    "LDAP://cn=BarrAdam,OU=hr,dc=na,dc=fabrikam,dc=com", vbNullString

Moving a User Account to a New Domain

Uses the MoveHere method of IADsContainer to move a user account to another domain. Note that there are a number of restrictions associated with performing this type of move operation. For details, see the Directory Services Platform SDK.

Set objOU = GetObject("LDAP://ou=management,dc=na,dc=fabrikam,dc=com")
objOU.MoveHere _
    "LDAP://cn=AckermanPilar,OU=management,dc=fabrikam,dc=com", vbNullString

Preventing a User From Changing His or Her Password

Enables the User Cannot Change Password option, which prevents the user from changing their password.

Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6
Const ADS_ACEFLAG_OBJECT_TYPE_PRESENT = &H1
Const CHANGE_PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}"
Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
Set objSD = objUser.Get("ntSecurityDescriptor")
Set objDACL = objSD.DiscretionaryAcl
arrTrustees = array("nt authority\self", "EVERYONE")

For Each strTrustee in arrTrustees
  Set objACE = CreateObject("AccessControlEntry")
    objACE.Trustee = strTrustee
  objACE.AceFlags = 0
  objACE.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT
  objACE.Flags = ADS_ACEFLAG_OBJECT_TYPE_PRESENT
  objACE.ObjectType = CHANGE_PASSWORD_GUID
  objACE.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
  objDACL.AddAce objACE
Next

objSD.DiscretionaryAcl = objDACL
objUser.Put "nTSecurityDescriptor", objSD
objUser. SetInfo

Requiring a Password Change

Forces a user to change their password the next time they logon.

Set objUser = GetObject _
    ("LDAP://CN=myerken,OU=management,DC=Fabrikam,DC=com")
objUser.Put "pwdLastSet", 0
objUser.SetInfo

Requiring a User to Logon on Using a Smartcard

Configures the MyerKen user account so that the user must use a smartcard in order to logon to Active Directory.

Const ADS_UF_SMARTCARD_REQUIRED = &h40000
Set objUser = GetObject _
  ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

intUAC = objUser.Get("userAccountControl")

If (intUAC AND ADS_UF_SMARTCARD_REQUIRED) = 0 Then
  objUser.Put "userAccountControl", intUAC XOR ADS_UF_SMARTCARD_REQUIRED
  objUser.SetInfo
End If

Retrieving Organization Information

Retrieves user account attributes found on the Organization page of the user account object in Active Directory Users and Computers.

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strTitle = objUser.Get("title")
strDepartment = objUser.Get("department")
strCompany = objUser.Get("company")
strManager = objUser.Get("manager")

strDirectReports = _
  objUser.GetEx("directReports")

WScript.echo "title: " & strTitle
WScript.echo "department: " & strDepartment
WScript.echo "company: " & strCompany
WScript.echo "manager: " & strManager

For Each strValue in strDirectReports
  WScript.echo "directReports: " & strValue
Next

Retrieving User Account Account Properties

Retrieves user account attributes found on the Account page of the user account object in Active Directory Users and Computers.

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strUserPrincipalName = objUser.Get("userPrincipalName")
strSAMAccountName = objUser.Get("sAMAccountName")
strUserWorkstations = objUser.Get("userWorkstations")

Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")
objDomain.GetInfoEx Array("dc"), 0
strDC = objDomain.Get("dc")

WScript.echo "userPrincipalName: " & strUserPrincipalName
WScript.echo "sAMAccountName: " & strSAMAccountName
WScript.echo "UserWorkstations: " & strUserWorkstations
WScript.echo "dc: " & strDC

Retrieving User Profile Properties

Retrieves user account attributes found on the Profile page of the user account object in Active Directory users and Computers.

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.GetInfo

strProfilePath = objUser.Get("profilePath")
strScriptPath = objUser.Get("scriptPath")
strHomeDirectory = objUser.Get("homeDirectory")
strHomeDrive = objUser.Get("homeDrive")

WScript.echo "profilePath: " & strProfilePath
WScript.echo "scriptPath: " & strScriptPath
WScript.echo "homeDirectory: " & strHomeDirectory
WScript.echo "homeDrive: " & strHomeDrive

Setting an Account Expiration Date

Configures a user account to expire on 3/30/2003.

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
objUser.AccountExpirationDate = "03/30/2003"
objUser.SetInfo

Setting a Password So It Never Expires

Configures the domain password for a user account to ensure that the password will never expire.

Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000

Set objUser = GetObject _
    ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")

If ADS_UF_DONT_EXPIRE_PASSWD AND intUAC Then
    Wscript.Echo "Already enabled"
Else
    objUser.Put "userAccountControl", intUAC XOR _
        ADS_UF_DONT_EXPIRE_PASSWD
    objUser.SetInfo
    WScript.Echo "Password never expires is now enabled"
End If

Setting the Primary Group for a User

Sets the primary group for the MyerKen Active Directory user account to MgmtUniversal.

Const ADS_PROPERTY_APPEND = 3

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")

Set objGroup = GetObject _
    ("LDAP://cn=MgmtUniversal,ou=Management,dc=NA,dc=fabrikam,dc=com")
objGroup.GetInfoEx Array("primaryGroupToken"), 0
intPrimaryGroupToken = objGroup.Get("primaryGroupToken")

objGroup.PutEx ADS_PROPERTY_APPEND, _
   "member", Array("cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objGroup.SetInfo
objUser.Put "primaryGroupID", intPrimaryGroupToken

objUser.SetInfo

Setting a Users Password

Configures a new password for a user.

Set objUser = GetObject _
 ("LDAP://cn=MyerKen,ou=management,dc=fabrikam,dc=com")
objUser.SetPassword "i5A2sj*!"

Unlocking an Active Directory User Account

Unlocks the MyerKen Active Directory user account.

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.IsAccountLocked = False
objUser.SetInfo

Writing User Account Properties

Configures general attributes for a user account.

Set objUser = GetObject _
  ("LDAP://cn=myerken,ou=management,dc=fabrikam,dc=com")

objUser.Put "userPrincipalName", "MyerKen@fabrikam.com"
objUser.Put "sAMAccountName", "MyerKen01"
objUser.Put "userWorkstations", "wks1,wks2,wks3"

1 thought on “active directory cheatsheet”

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Contact Us