View Scripts of choice:

Script Library

Copy an Active Directory Computer Account
About: Active Directory

Retrieves the attributes of an existing computer object and copies the attributes to a new computer object created by the script.

Set objCompt = _
    GetObject("LDAP://cn=Computers,dc=NA,dc=fabrikam,dc=com")
Set objComptCopy = objCompt.Create("computer", "cn=SEA-SQL-01")
objComptCopy.Put "sAMAccountName", "sea-sql-01"
objComptCopy.SetInfo
 
Set objComptTemplate = GetObject _
    ("LDAP://cn=SEA-PM-01,cn=Computers,dc=NA,dc=fabrikam,dc=com")
arrAttributes = Array("description", "location")
 
For Each strAttrib in arrAttributes
    strValue = objComptTemplate.Get(strAttrib)
    objComptCopy.Put strAttrib, strValue
Next
 
objComptCopy.SetInfo
Create a Computer Account For a Specific User
About: Active Directory

Creates and enables a computer account in Active Directory. A specific, authenticated user can then use this account to add his or her workstation to the domain.

strComputer = "atl-pro-002"
strComputerUser = "fabrikam\lewjudy"
 
Const ADS_UF_PASSWD_NOTREQD = &h0020
Const ADS_UF_WORKSTATION_TRUST_ACCOUNT = &h1000
Const ADS_ACETYPE_ACCESS_ALLOWED = &h0
Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &h5
Const ADS_FLAG_OBJECT_TYPE_PRESENT = &h1
Const ADS_RIGHT_GENERIC_READ = &h80000000
Const ADS_RIGHT_DS_SELF = &h8
Const ADS_RIGHT_DS_WRITE_PROP = &h20
Const ADS_RIGHT_DS_CONTROL_ACCESS = &h100
 
Const ALLOWED_TO_AUTHENTICATE = _
    "{68B1D179-0D15-4d4f-AB71-46152E79A7BC}"
Const RECEIVE_AS = "{AB721A56-1E2f-11D0-9819-00AA0040529B}"
Const SEND_AS = "{AB721A54-1E2f-11D0-9819-00AA0040529B}"
Const USER_CHANGE_PASSWORD = _
    "{AB721A53-1E2f-11D0-9819-00AA0040529b}"
Const USER_FORCE_CHANGE_PASSWORD = _
    "{00299570-246D-11D0-A768-00AA006E0529}"
Const USER_ACCOUNT_RESTRICTIONS = _
    "{4C164200-20C0-11D0-A768-00AA006E0529}"
Const VALIDATED_DNS_HOST_NAME = _
    "{72E39547-7B18-11D1-ADEF-00C04FD8D5CD}"
Const VALIDATED_SPN = "{F3A64788-5306-11D1-A9C5-0000F80367C1}"
 
Set objRootDSE = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Computers," & _
    objRootDSE.Get("defaultNamingContext"))
 
Set objComputer = objContainer.Create _
    ("Computer", "cn=" & strComputer)
objComputer.Put "sAMAccountName", strComputer & "$"
objComputer.Put "userAccountControl", _
    ADS_UF_PASSWD_NOTREQD Or ADS_UF_WORKSTATION_TRUST_ACCOUNT
objComputer.SetInfo
 
Set objSecurityDescriptor = objComputer.Get("ntSecurityDescriptor")
Set objDACL = objSecurityDescriptor.DiscretionaryAcl
 
Set objACE1 = CreateObject("AccessControlEntry")
objACE1.Trustee    = strComputerUser
objACE1.AccessMask = ADS_RIGHT_GENERIC_READ
objACE1.AceFlags   = 0
objACE1.AceType    = ADS_ACETYPE_ACCESS_ALLOWED
 
Set objACE2 = CreateObject("AccessControlEntry")
objACE2.Trustee    = strComputerUser
objACE2.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE2.AceFlags   = 0
objACE2.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE2.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE2.ObjectType = ALLOWED_TO_AUTHENTICATE
 
Set objACE3 = CreateObject("AccessControlEntry")
objACE3.Trustee    = strComputerUser
objACE3.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE3.AceFlags   = 0
objACE3.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE3.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE3.ObjectType = RECEIVE_AS
 
Set objACE4 = CreateObject("AccessControlEntry")
objACE4.Trustee    = strComputerUser
objACE4.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE4.AceFlags   = 0
objACE4.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE4.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE4.ObjectType = SEND_AS
 
Set objACE5 = CreateObject("AccessControlEntry")
objACE5.Trustee    = strComputerUser
objACE5.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE5.AceFlags   = 0
objACE5.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE5.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE5.ObjectType = USER_CHANGE_PASSWORD
 
Set objACE6 = CreateObject("AccessControlEntry")
objACE6.Trustee    = strComputerUser
objACE6.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS
objACE6.AceFlags   = 0
objACE6.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE6.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE6.ObjectType = USER_FORCE_CHANGE_PASSWORD
 
Set objACE7 = CreateObject("AccessControlEntry")
objACE7.Trustee    = strComputerUser
objACE7.AccessMask = ADS_RIGHT_DS_WRITE_PROP
objACE7.AceFlags   = 0
objACE7.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE7.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE7.ObjectType = USER_ACCOUNT_RESTRICTIONS
 
Set objACE8 = CreateObject("AccessControlEntry")
objACE8.Trustee    = strComputerUser
objACE8.AccessMask = ADS_RIGHT_DS_SELF
objACE8.AceFlags   = 0
objACE8.AceType    = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE8.Flags      = ADS_FLAG_OBJECT_TYPE_PRESENT
objACE8.ObjectType = VALIDATED_DNS_HOST_NAME
 
Set objACE9 = CreateObject("AccessControlEntry")
objACE9.Trustee    = strComputerUser
objACE9.AccessMask = ADS_RIGHT_DS_SELF
objACE9.AceFlags   = 0
objACE9.AceType  = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
objACE9.Flags  =  ADS_FLAG_OBJECT_TYPE_PRESENT
objACE9.ObjectType = VALIDATED_SPN
 
objDACL.AddAce objACE1
objDACL.AddAce objACE2
objDACL.AddAce objACE3
objDACL.AddAce objACE4
objDACL.AddAce objACE5
objDACL.AddAce objACE6
objDACL.AddAce objACE7
objDACL.AddAce objACE8
objDACL.AddAce objACE9
 
objSecurityDescriptor.DiscretionaryAcl = objDACL
objComputer.Put "ntSecurityDescriptor", objSecurityDescriptor
objComputer.SetInfo
Delete a Computer Account
About: Active Directory

Deletes an individual computer account in Active Directory.

strComputer = "atl-pro-040"

set objComputer = GetObject("LDAP://CN=" & strComputer & _
    ",CN=Computers,DC=fabrikam,DC=com")
objComputer.DeleteObject (0)
Disable a Global Catalog Server
About: Active Directory

Disables the global catalog service on the domain controller atl-dc-01.

strComputer = "atl-dc-01"
 
Const NTDSDSA_OPT_IS_GC = 1
 
Set objRootDSE = GetObject("LDAP://" & strComputer & "/rootDSE")
strDsServiceDN = objRootDSE.Get("dsServiceName")
Set objDsRoot  = GetObject _
    ("LDAP://" & strComputer & "/" & strDsServiceDN)
intOptions = objDsRoot.Get("options")
 
If intOptions And NTDSDSA_OPT_IS_GC Then
    objDsRoot.Put "options", intOptions Xor NTDSDSA_OPT_IS_GC
    objDsRoot.Setinfo
End If
Enable a Global Catalog Server
About: Active Directory

Enables the global catalog service on the domain controller atl-dc-01.

strComputer = "atl-dc-01"
 
Const NTDSDSA_OPT_IS_GC = 1
 
Set objRootDSE = GetObject("LDAP://" & strComputer & "/RootDSE")
strDsServiceDN = objRootDSE.Get("dsServiceName")
Set objDsRoot  = GetObject _
    ("LDAP://" & strComputer & "/" & strDsServiceDN)
intOptions = objDsRoot.Get("options")
 
If (intOptions And NTDSDSA_OPT_IS_GC) = FALSE Then
    objDsRoot.Put "options" , intOptions Or NTDSDSA_OPT_IS_GC
    objDsRoot.Setinfo
End If
Join a Computer to a Domain
About: Active Directory

Joins the local computer to a domain and creates the computer's account in Active Directory.

Const JOIN_DOMAIN = 1
Const ACCT_CREATE = 2
Const ACCT_DELETE = 4
Const WIN9X_UPGRADE = 16
Const DOMAIN_JOIN_IF_JOINED = 32
Const JOIN_UNSECURE = 64
Const MACHINE_PASSWORD_PASSED = 128
Const DEFERRED_SPN_SET = 256
Const INSTALL_INVOCATION = 262144
 
strDomain = "FABRIKAM"
strPassword = "ls4k5ywA"
strUser = "shenalan"
 
Set objNetwork = CreateObject("WScript.Network")
strComputer = objNetwork.ComputerName
 
Set objComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & _
    strComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & _
        strComputer & "'")
 
ReturnValue = objComputer.JoinDomainOrWorkGroup(strDomain, _
    strPassword, strDomain & "\" & strUser, NULL, _
        JOIN_DOMAIN + ACCT_CREATE)
List All Computer Accounts in Active Directory
About: Active Directory

Returns the name and location for all the computer accounts in Active Directory.

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = _
    "Select Name, Location from 'LDAP://DC=fabrikam,DC=com' " _
        & "Where objectClass='computer'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo "Computer Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "Location: " & objRecordSet.Fields("Location").Value
    objRecordSet.MoveNext
Loop
List FSMO Role Holders
About: Active Directory

Identifies the Active Directory domain controllers providing the five FSMO roles: Schema Master, Domain Naming Master, PDC Emulator, RID Master, and Infrastructure Master.

Set objRootDSE = GetObject("LDAP://rootDSE")
 
Set objSchema = GetObject _
    ("LDAP://" & objRootDSE.Get("schemaNamingContext"))
strSchemaMaster = objSchema.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strSchemaMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Forest-wide Schema Master FSMO: " & objComputer.Name
 
Set objNtds = Nothing
Set objComputer = Nothing
 
Set objPartitions = GetObject("LDAP://CN=Partitions," & _ 
    objRootDSE.Get("configurationNamingContext"))
strDomainNamingMaster = objPartitions.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strDomainNamingMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Forest-wide Domain Naming Master FSMO: " & objComputer.Name
 
Set objDomain = GetObject _
    ("LDAP://" & objRootDSE.Get("defaultNamingContext"))
strPdcEmulator = objDomain.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strPdcEmulator)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's PDC Emulator FSMO: " & objComputer.Name
 
Set objRidManager = GetObject("LDAP://CN=RID Manager$,CN=System," & _
    objRootDSE.Get("defaultNamingContext"))
strRidMaster = objRidManager.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strRidMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's RID Master FSMO: " & objComputer.Name
 
Set objInfrastructure = GetObject("LDAP://CN=Infrastructure," & _
    objRootDSE.Get("defaultNamingContext"))
strInfrastructureMaster = objInfrastructure.Get("fSMORoleOwner")
Set objNtds = GetObject("LDAP://" & strInfrastructureMaster)
Set objComputer = GetObject(objNtds.Parent)
WScript.Echo "Domain's Infrastructure Master FSMO: " & objComputer.Name
List Selected Computer Account Attributes
About: Active Directory

Demonstration script that retrieves the location and description attributes for a computer account in Active Directory.

On Error Resume Next

Set objComputer = GetObject _
    ("LDAP://CN=atl-dc-01,CN=Computers,DC=fabrikam,DC=com")

objProperty = objComputer.Get("Location")
If IsNull(objProperty) Then
    Wscript.Echo "The location has not been set."
Else
    Wscript.Echo "Location: " & objProperty
    objProperty = Null
End If

objProperty = objComputer.Get("Description")
If IsNull(objProperty) Then
    Wscript.Echo "The description has not been set."
Else
    Wscript.Echo "Description: " & objProperty
    objProperty = Null
End If
Modify Computer Location Attribute
About: Active Directory

Demonstration script that changes the location attribute for a computer account in Active Directory.

Set objComputer = GetObject _ 
    ("LDAP://CN=atl-dc-01,CN=Computers,DC=fabrikam,DC=com")

objComputer.Put "Location" , "Building 37, Floor 2, Room 2133"
objComputer.SetInfo
Move a Computer Account
About: Active Directory

Moves a computer account from the Computers container in Active Directory to the Finance OU in the same domain.

Set objNewOU = GetObject("LDAP://OU=Finance,DC=fabrikam,DC=com")

Set objMoveComputer = objNewOU.MoveHere _
    ("LDAP://CN=atl-pro-03,CN=Computers,DC=fabrikam,DC=com", "CN=atl-pro-03")
Move a Computer Account to a New Domain
About: Active Directory

Uses the MoveHere method to move an object 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://cn=Computers,dc=NA,dc=fabrikam,dc=com")

objOU.MoveHere "LDAP://cn=Computer01,cn=Users,dc=fabrikam,dc=com", _
    vbNullString
Rename a Computer Account
About: Active Directory

Renames an Active Directory computer account.

Set objNewOU = GetObject("LDAP://OU=Finance,DC=fabrikam,DC=com")

Set objMoveComputer = objNewOU.MoveHere _
    ("LDAP://CN=atl-pro-037,OU=Finance,DC=fabrikam,DC=com", _
        "CN=atl-pro-003")
Rename a Computer and Computer Account
About: Active Directory

Renames a computer and its corresponding Active Directory computer account. Requires Windows XP or Windows Server 2003, and must be run on the local computer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colComputers = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

For Each objComputer in colComputers
    err = objComputer.Rename("WebServer")
Next
Reset a Computer Account Password
About: Active Directory

Resets a computer account password in Active Directory.

Set objComputer = GetObject _
    ("LDAP://CN=atl-dc-01,CN=Computers,DC=Reskit,DC=COM")

objComputer.SetPassword "atl-dc-01$"
Search for Specific Computer Accounts
About: Active Directory

Returns the name and location for all the computers in the domain that are running Windows Server 2003.

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    "Select Name, Location, operatingSystemVersion from " & _
        "'LDAP://DC=fabrikam,DC=com' where objectClass='computer'" & _
            " and operatingSystemVersion = '5.1 (3600)'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo "Computer Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "Location: " & objRecordSet.Fields("Location").Value
    objRecordSet.MoveNext
Loop
Verify Computer Role
About: Active Directory

Returns the basic role (domain controller, member server, workstation, etc.) for a computer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colComputers = objWMIService.ExecQuery _
    ("Select DomainRole from Win32_ComputerSystem")

For Each objComputer in colComputers
    Select Case objComputer.DomainRole 
        Case 0 
            strComputerRole = "Standalone Workstation"
        Case 1        
            strComputerRole = "Member Workstation"
        Case 2
            strComputerRole = "Standalone Server"
        Case 3
            strComputerRole = "Member Server"
        Case 4
            strComputerRole = "Backup Domain Controller"
        Case 5
            strComputerRole = "Primary Domain Controller"
    End Select
    Wscript.Echo strComputerRole
Next
Verify that a Computer is a Global Catalog Server
About: Active Directory

Indicates whether or not the atl-dc-01 domain controller is a global catalog server.

strComputer = "atl-dc-01"
 
Const NTDSDSA_OPT_IS_GC = 1
 
Set objRootDSE = GetObject("LDAP://" & strComputer & "/rootDSE")
strDsServiceDN = objRootDSE.Get("dsServiceName")
Set objDsRoot  = GetObject("LDAP://" & strComputer & "/" & strDsServiceDN)
intOptions = objDsRoot.Get("options")
 
If intOptions And NTDSDSA_OPT_IS_GC Then
    WScript.Echo strComputer & " is a global catalog server."
Else
    Wscript.Echo strComputer & " is not a global catalog server."
End If
List Domain Information Using WMI
About: Active Directory

Retrieves information about domains discovered on the network.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_NTDomain")

For Each objItem in colItems
    Wscript.Echo "Client Site Name: " & objItem.ClientSiteName
    Wscript.Echo "DC Site Name: " & objItem.DcSiteName
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "DNS Forest Name: " & objItem.DnsForestName
    Wscript.Echo "Domain Controller Address: " & _
        objItem.DomainControllerAddress
    Wscript.Echo "Domain Controller Address Type: " & _
        objItem.DomainControllerAddressType
    Wscript.Echo "Domain Controller Name: " & objItem.DomainControllerName
    Wscript.Echo "Domain GUID: " & objItem.DomainGuid
    Wscript.Echo "Domain Name: " & objItem.DomainName
    Wscript.Echo "DS Directory Service Flag: " & objItem.DSDirectoryServiceFlag
    Wscript.Echo "DS DNS Controller Flag: " & objItem.DSDnsControllerFlag
    Wscript.Echo "DS DNS Domain Flag: " & objItem.DSDnsDomainFlag
    Wscript.Echo "DS DNS Forest Flag: " & objItem.DSDnsForestFlag
    Wscript.Echo "DS Global Catalog Flag: " & objItem.DSGlobalCatalogFlag
    Wscript.Echo "DS Kerberos Distribution Center Flag: " & _
        objItem.DSKerberosDistributionCenterFlag
    Wscript.Echo "DS Primary Domain Controller Flag: " & _
        objItem.DSPrimaryDomainControllerFlag
    Wscript.Echo "DS Time Service Flag: " & objItem.DSTimeServiceFlag
    Wscript.Echo "DS Writable Flag: " & objItem.DSWritableFlag
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Primary Owner Contact: " & objItem.PrimaryOwnerContact
    Wscript.Echo
Next
Add 1000 Sample Users to a Security Group
About: Active Directory

Demonstration script that creates a security group named Group1, and adds one thousand users (UserNo1 through UserNo10000) to that group. This script is not intended for use in a production environment.

Const ADS_PROPERTY_APPEND = 3 

Set objRootDSE = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://cn=Users," & _
    objRootDSE.Get("defaultNamingContext"))
Set objGroup = objContainer.Create("Group", "cn=Group1")
objGroup.Put "sAMAccountName","Group1"
objGroup.SetInfo 

For i = 1 To 1000
    strDN = ",cn=Users," & objRootDSE.defaultNamingContext
    objGroup.PutEx ADS_PROPERTY_APPEND, "member", _
        Array("cn=UserNo" & i & strDN)
    objGroup.SetInfo
Next
WScript.Echo "Group1 created and 1000 Users added to the group."
Add a User to Two Security Groups
About: Active Directory

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
Add New Members to a Security Group
About: Active Directory

Adds two groups (Executives and Scientists) and one user account (MyerKen) to the Sea-Users group in Active Directory.

Const ADS_PROPERTY_APPEND = 3 
 
Set objGroup = GetObject _
  ("LDAP://cn=Sea-Users,cn=Users,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.PutEx ADS_PROPERTY_APPEND, "member", _
    Array("cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com", _
        "cn=Executives,ou=Management,dc=NA,dc=fabrikam,dc=com", _ 
            "cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
objGroup.SetInfo
Assign a Group Manager
About: Active Directory

Assigns user MyerKen as the manager of an Active Directory security group named Scientists.

Set objGroup = GetObject _
  ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
 
objGroup.Put "managedBy", "cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com"
objGroup.SetInfo
Change the Scope of a Security Group
About: Active Directory

Changes a global distribution group named Scientists to a universal security group.

Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2
Const ADS_GROUP_TYPE_LOCAL_GROUP = &h4
Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &h8
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.Put "groupType", _
    ADS_GROUP_TYPE_GLOBAL_GROUP + ADS_GROUP_TYPE_SECURITY_ENABLED
 
objGroup.SetInfo
Create a Domain Local Distribution Group
About: Active Directory

Creates a domain local Active Directory distribution group named Vendors.

Const ADS_GROUP_TYPE_LOCAL_GROUP = &h4

Set objOU = GetObject("LDAP://ou=HR,dc=NA,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=Vendors")

objGroup.Put "sAMAccountName", "vendors"
objGroup.Put "groupType", ADS_GROUP_TYPE_LOCAL_GROUP
objGroup.SetInfo
Create a Domain Local Security Group
About: Active Directory

Creates a domain local Active Directory security group named DB-Servers.

Const ADS_GROUP_TYPE_LOCAL_GROUP = &h4
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000

Set objOU = GetObject("LDAP://cn=Computers,dc=NA,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=DB-Servers")

objGroup.Put "sAMAccountName", "DBServers"
objGroup.Put "groupType", ADS_GROUP_TYPE_LOCAL_GROUP Or _
    ADS_GROUP_TYPE_SECURITY_ENABLED
objGroup.SetInfo
Create a Global Distribution Group
About: Active Directory

Creates a global Active Directory distribution group named Scientists.

Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2

Set objOU = GetObject("LDAP://ou=R&D,dc=NA,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=Scientists")

objGroup.Put "sAMAccountName", "scientists"
objGroup.Put "groupType", ADS_GROUP_TYPE_GLOBAL_GROUP
objGroup.SetInfo
Create a Global Security Group
About: Active Directory

Creates a global Active Directory security group named HR-Employees.

Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000

Set objOU = GetObject("LDAP://ou=HR,dc=NA,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=HR-Employees")

objGroup.Put "sAMAccountName", "HRStaff"
objGroup.Put "groupType", ADS_GROUP_TYPE_GLOBAL_GROUP Or _
    ADS_GROUP_TYPE_SECURITY_ENABLED
objGroup.SetInfo
Create a Universal Distribution Group
About: Active Directory

Creates a universal Active Directory distribution group named Customers.

Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &h8

Set objOU = GetObject("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=Customers")

objGroup.Put "sAMAccountName", "customers"
objGroup.Put "groupType", ADS_GROUP_TYPE_UNIVERSAL_GROUP
objGroup.SetInfo
Create a Universal Security Group
About: Active Directory

Creates a universal Active Directory security group named All-Employees.

Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &h8
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000

Set objOU = GetObject("LDAP://cn=Users,dc=NA,dc=fabrikam,dc=com")
Set objGroup = objOU.Create("Group", "cn=All-Employees")

objGroup.Put "sAMAccountName", "AllEmployees"
objGroup.Put "groupType", ADS_GROUP_TYPE_UNIVERSAL_GROUP Or _
    ADS_GROUP_TYPE_SECURITY_ENABLED
objGroup.SetInfo
Delete a Group from Active Directory
About: Active Directory

Deletes a group named atl-users from the HR organizational unit in the domain fabrikam.com.

Set objOU = GetObject("LDAP://ou=hr,dc=fabrikam,dc=com")

objOU.Delete "group", "cn=atl-users"
List All the Members of a Group
About: Active Directory

Returns the members of an Active Directory group named Scientists.

On Error Resume Next
 
Set objGroup = GetObject _
  ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
objGroup.GetInfo
 
arrMemberOf = objGroup.GetEx("member")
 
WScript.Echo "Members:"
For Each strMember in arrMemberOf
    WScript.echo strMember
Next
List Group Memberships for All the Users in an OU
About: Active Directory

Retrieves the memberOf and primaryGroupID attributes of a user account to display group membership. Note that the primaryGroupID attribute contains an integer that maps to the name of the primary group. The memberOf attribute does not contain the name of the primary group of which the user is a member.

On Error Resume Next

Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D

Set objOU = GetObject _
    ("LDAP://cn=Users,dc=NA,dc=fabrikam,dc=com")
  
ObjOU.Filter= Array("user")
 
For Each objUser in objOU
    WScript.Echo objUser.cn & " is a member of: " 
    WScript.Echo vbTab & "Primary Group ID: " & _
        objUser.Get("primaryGroupID")
  
    arrMemberOf = objUser.GetEx("memberOf")
  
    If Err.Number <>  E_ADS_PROPERTY_NOT_FOUND Then
        For Each Group in arrMemberOf
            WScript.Echo vbTab & Group
        Next
    Else
        WScript.Echo vbTab & "memberOf attribute is not set"
        Err.Clear
    End If
    Wscript.Echo 
Next
List Group Object Information
About: Active Directory

Retrieves the information found on the Object page in Active Directory Users and Computers for a security group named Scientists.

Set objGroup = GetObject _
  ("GC://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
 
strWhenCreated = objGroup.Get("whenCreated")
strWhenChanged = objGroup.Get("whenChanged")
 
Set objUSNChanged = objGroup.Get("uSNChanged")
dblUSNChanged = _
    Abs(objUSNChanged.HighPart * 2^32 + objUSNChanged.LowPart)
 
Set objUSNCreated = objGroup.Get("uSNCreated")
dblUSNCreated = _
    Abs(objUSNCreated.HighPart * 2^32 + objUSNCreated.LowPart)
 
objGroup.GetInfoEx Array("canonicalName"), 0
arrCanonicalName = objGroup.GetEx("canonicalName")
 
WScript.echo "CanonicalName of object:"
For Each strValue in arrCanonicalName
    WScript.Echo vbTab & strValue
Next
WScript.Echo 
 
WScript.Echo "Object class: " & objGroup.Class 
WScript.Echo "When Created: " & strWhenCreated & " (Created - GMT)"
WScript.Echo "When Changed: " & strWhenChanged & " (Modified - GMT)"
WScript.Echo 
WScript.Echo "USN Changed: " & dblUSNChanged & " (USN Current)"
WScript.Echo "USN Created: " & dblUSNCreated & " (USN Original)"
List Other Groups a Group Belongs To
About: Active Directory

Returns a list of all the groups that the Active Directory security group Scientists is a member of.

On Error Resume Next
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
objGroup.GetInfo
 
arrMembersOf = objGroup.GetEx("memberOf")
 
WScript.Echo "MembersOf:"
For Each strMemberOf in arrMembersOf
    WScript.Echo strMemberOf
Next
List the Active Directory Groups a User Belongs To
About: Active Directory

Returns a list of all the Active Directory security groups (including the primary group) that include the MyerKen user account as a member.

On Error Resume Next
Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
intPrimaryGroupID = objUser.Get("primaryGroupID")
arrMemberOf = objUser.GetEx("memberOf")
 
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "The memberOf attribute is not set."
Else
    WScript.Echo "Member of: "
    For Each Group in arrMemberOf
        WScript.Echo Group
    Next
End If
 
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    ";(objectCategory=Group);" & _
        "distinguishedName,primaryGroupToken;subtree"  
Set objRecordSet = objCommand.Execute
  
Do Until objRecordset.EOF
    If objRecordset.Fields("primaryGroupToken") = intPrimaryGroupID Then
        WScript.Echo "Primary group:"
        WScript.Echo objRecordset.Fields("distinguishedName") & _
            " (primaryGroupID: " & intPrimaryGroupID & ")"
    End If
    objRecordset.MoveNext
Loop
 
objConnection.Close
List the Attributes of the Group Class
About: Active Directory

Returns a list of mandatory and optional attributes of the group class (as stored in the Active Directory schema).

Set objGroupClass = GetObject("LDAP://schema/group")
Set objSchemaClass = GetObject(objGroupClass.Parent)
 
i = 0
WScript.Echo "Mandatory attributes:"
For Each strAttribute in objGroupClass.MandatoryProperties
    i= i + 1
    WScript.Echo i & vbTab & strAttribute
    Set objAttribute = objSchemaClass.GetObject("Property",  strAttribute)
    WScript.Echo " (Syntax: " & objAttribute.Syntax & ")"
    If objAttribute.MultiValued Then
        WScript.Echo " Multivalued"
    Else
        WScript.Echo " Single-valued"
    End If
Next
 
WScript.Echo VbCrLf & "Optional attributes:"
For Each strAttribute in objGroupClass.OptionalProperties
    i= i + 1
    Wscript.Echo i & vbTab & strAttribute
    Set objAttribute = objSchemaClass.GetObject("Property",  strAttribute)
    Wscript.Echo " [Syntax: " & objAttribute.Syntax & "]"
    If objAttribute.MultiValued Then
        WScript.Echo " Multivalued"
    Else
        WScript.Echo " Single-valued"
    End If
Next
List the General Properties of a Group
About: Active Directory

Reads the values found on the General Properties page in Active Directory Users and Computers for a group named Scientists.

On Error Resume Next

Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2
Const ADS_GROUP_TYPE_LOCAL_GROUP = &h4
Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &h8
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")

WScript.Echo "Name: " & objGroup.Name
WScript.Echo "SAM Account Name: " & objGroup.SAMAccountName
WScript.Echo "Mail: " & objGroup.Mail
WScript.Echo "Info: " & objGroup.Info
 
If intGroupType AND ADS_GROUP_TYPE_LOCAL_GROUP Then
    WScript.Echo "Group scope: Domain local"
ElseIf intGroupType AND ADS_GROUP_TYPE_GLOBAL_GROUP Then
    WScript.Echo "Group scope: Global"
ElseIf intGroupType AND ADS_GROUP_TYPE_UNIVERSAL_GROUP Then
    WScript.Echo "Group scope: Universal"
Else
    WScript.Echo "Group scope: Unknown"
End If
 
If intGroupType AND ADS_GROUP_TYPE_SECURITY_ENABLED Then
    WScript.Echo "Group type: Security group"
Else
    WScript.Echo "Group type: Distribution group"
End If
 
For Each strValue in objGroup.Description
    WScript.Echo "Description: " & strValue
Next
List the Managed By Information for a Group
About: Active Directory

Returns information about the manager assigned to an Active Directory security group named Scientists.

On Error Resume Next
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
 
strManagedBy = objGroup.Get("managedBy")
 
If IsEmpty(strManagedBy) = TRUE Then
    WScript.Echo "No user account is assigned to manage " & _
        "this group."
Else
    Set objUser = GetObject("LDAP://" & strManagedBy)

    Call GetUpdateMemberList
 
    WScript.Echo "Office: " & _
        objUser.physicalDeliveryOfficeName  
    WScript.Echo "Street Address: " & objUser.streetAddress
    WScript.Echo "Locality: " & objUser.l
    WScript.Echo "State/Province: " & objUser.st
    WScript.Echo "Country: " & objUser.c
    WScript.Echo "Telephone Number: " & objUser.telephoneNumber
    WScript.Echo "Fax Number: " & _
        objUser.facsimileTelephoneNumber
End If
 
Sub GetUpdateMemberList
    Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5 
    Const Member_SchemaIDGuid = "{BF9679C0-0DE6-11D0-A285-00AA003049E2}"
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    objUser.GetInfoEx Array("canonicalName"),0
    strCanonicalName = objUser.Get("canonicalName")
    strDomain = Mid(strCanonicalName,1,InStr(1,strCanonicalName,".")-1)
    strSAMAccountName = objUser.Get("sAMAccountName")
 
    Set objNtSecurityDescriptor = objGroup.Get("ntSecurityDescriptor")
    Set objDiscretionaryAcl = objNtSecurityDescriptor.DiscretionaryAcl
 
    blnMatch = False
    For Each objAce In objDiscretionaryAcl
        If LCase(objAce.Trustee) = _
            LCase(strDomain & "\" & strSAMAccountName) AND _
            objAce.ObjectType =  Member_SchemaIDGuid AND _
                objAce.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT AND _
                    objAce.AccessMask And ADS_RIGHT_DS_WRITE_PROP Then
                        blnMatch = True
        End If  
    Next
    If blnMatch Then 
        WScript.Echo "Manager can update the member list"
    Else
        WScript.Echo "Manager cannot update the member list."
    End If
End Sub
List the Owner of a Group
About: Active Directory

Returns the owner of an Active Directory security group named Scientists.

Set objGroup = GetObject _
  ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
 
Set objNtSecurityDescriptor = objGroup.Get("ntSecurityDescriptor")
 
WScript.Echo "Owner Tab"
WScript.Echo "Current owner of this item: " & objNtSecurityDescriptor.Owner
List the Primary Group for a User Account
About: Active Directory

Reports the primary group for the MyerKen Active Directory user account.

On Error Resume Next

Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
intPrimaryGroupID = objUser.Get("primaryGroupID")
 
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    ";(objectCategory=Group);" & _
        "distinguishedName,primaryGroupToken;subtree"  
Set objRecordSet = objCommand.Execute
  
Do Until objRecordset.EOF
    If objRecordset.Fields("primaryGroupToken") = intPrimaryGroupID Then
        WScript.Echo "Primary group:"
        WScript.Echo objRecordset.Fields("distinguishedName") & _
            " (primaryGroupID: " & intPrimaryGroupID & ")"
    End If
    objRecordset.MoveNext
Loop
 
objConnection.Close
List the Security Descriptor for a Group
About: Active Directory

Returns information found on the security descriptor for the Active Directory group named Scientists.

Const SE_DACL_PROTECTED = &H1000 
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
 
Set objNtSecurityDescriptor = objGroup.Get("ntSecurityDescriptor")
 
intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
 
WScript.Echo "Permissions Tab"
strMessage = "Allow inheritable permissions from the parent to " & _
     "propogate to this object and all child objects " 
If (intNtSecurityDescriptorControl And SE_DACL_PROTECTED) Then
    Wscript.Echo strMessage & "is disabled."
Else
    WScript.Echo strMessage & "is enabled."
End If
WScript.Echo 
 
Set objDiscretionaryAcl = objNtSecurityDescriptor.DiscretionaryAcl
DisplayAceInformation objDiscretionaryAcl, "DACL"
 
Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_ACCESS_ALLOWED = &H0 
    Const ADS_ACETYPE_ACCESS_DENIED = &H1 
    Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5 
    Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6 
    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            WScript.Echo strType & " permission entry: " & intAceCount
            WScript.Echo "Name: " & objAce.Trustee
 
            intAceType = objAce.AceType
            If (intAceType = ADS_ACETYPE_ACCESS_ALLOWED Or _
                intAceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT) Then
                WScript.Echo "Type: Allow Access"
            ElseIf (intAceType = ADS_ACETYPE_ACCESS_DENIED Or _
                intAceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) Then
                WScript.Echo "Type: Deny Acess"
            Else
                WScript.Echo "Acess Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            WScript.Echo VbCr
        End If
    Next
End Sub
 
Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100
 
    WScript.Echo VbCrLf & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        WScript.Echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        WScript.Echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        WScript.Echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        WScript.Echo vbTab & "-Modify owner."
  
    WScript.Echo VbCrLf & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
       WScript.Echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        WScript.Echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        WScript.Echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        WScript.Echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        WScript.Echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        WScript.Echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        WScript.Echo vbTab & "-List a tree of objects."
 
    WScript.Echo VbCrLf & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
        WScript.Echo "-None"
    Else 
        If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
            WScript.Echo vbTab & "-Extended access rights."
        If (AccessMask And ADS_RIGHT_DS_SELF) Then
            WScript.Echo vbTab & "-Active Directory must validate a property "
            WScript.Echo vbTab & " write operation beyond the schema " & _
                "definition "
            WScript.Echo vbTab & " for the attribute."
      End If
    End If
End Sub
List the System Access Control List for a Group
About: Active Directory

Returns information found on the System Access Control List (SACL) for an Active Directory security group named Scientists.

Const SE_SACL_PROTECTED = &H2000 
Const ADS_SECURITY_INFO_OWNER = &H1 
Const ADS_SECURITY_INFO_GROUP = &H2
Const ADS_OPTION_SECURITY_MASK =&H3
Const ADS_SECURITY_INFO_DACL = &H4 
Const ADS_SECURITY_INFO_SACL = &H8
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")
 
objGroup.SetOption ADS_OPTION_SECURITY_MASK, ADS_SECURITY_INFO_OWNER _
    Or ADS_SECURITY_INFO_GROUP Or ADS_SECURITY_INFO_DACL _
    Or ADS_SECURITY_INFO_SACL
  
Set objNtSecurityDescriptor = objGroup.Get("ntSecurityDescriptor")
 
intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
 
WScript.Echo "Auditing Tab"
strMessage = "Allow inheritable auditing entries from" & _ 
    "the parent to "
strMessage = strMessage & "propogate to this object and all child objects "

If (intNtSecurityDescriptorControl And SE_SACL_PROTECTED) Then
    Wscript.Echo strMessage & "is disabled."
Else
    WScript.Echo strMessage & "is enabled."
End If
WScript.Echo 
 
Set objSacl = objNtSecurityDescriptor.SystemAcl
DisplayAceInformation objSacl, "SACL"
 
Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_SYSTEM_AUDIT = &H2 
    Const ADS_ACETYPE_SYSTEM_AUDIT_OBJECT = &H7 
  
    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            WScript.Echo strType & " permission entry: " & intAceCount
            WScript.Echo "Name: " & objAce.Trustee
 
            intAceType = objAce.AceType
            WScript.Echo "ACETYPE IS: " & intAceType
            If (intAceType = ADS_ACETYPE_SYSTEM_AUDIT or _
                intAceType = ADS_ACETYPE_SYSTEM_AUDIT_OBJECT) Then
                WScript.Echo "Type: Success or Failure Audit"
            Else
                WScript.Echo "Audit Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            WScript.Echo 
        End If
    Next
End Sub
 
Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100
 
    WScript.Echo VbCrLf & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        WScript.Echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        WScript.Echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        WScript.Echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        WScript.Echo vbTab & "-Modify owner."
  
    WScript.Echo VbCrLf & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
        WScript.Echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        WScript.Echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        WScript.Echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        WScript.Echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        WScript.Echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        WScript.Echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        WScript.Echo vbTab & "-List a tree of objects."
 
    WScript.Echo VbCrLf & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
            WScript.Echo "-None"
    Else 
        If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
            WScript.Echo vbTab & "-Extended access rights."
        If (AccessMask And ADS_RIGHT_DS_SELF) Then
            WScript.Echo vbTab & "-Active Directory must validate a property "
            WScript.Echo vbTab & " write operation beyond the schema " & _
                "definition "
            WScript.Echo vbTab & " for the attribute."
        End If
    End If
End Sub
Modify Group Attributes
About: Active Directory

Modifies both single-value (samAccountName, mail, info) and multi-value (description) attributes for a group named Scientists.

Const ADS_PROPERTY_UPDATE = 2 

Set objGroup = GetObject _
   ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.Put "sAMAccountName", "Scientist01"
objGroup.Put "mail", "YoungRob@fabrikam.com"
objGroup.Put "info", "Use this group for official communications " & _
  "with scientists who are contracted to work with Contoso.com."
objGroup.PutEx ADS_PROPERTY_UPDATE, _
    "description", Array("Scientist Mailing List")
objGroup.SetInfo
Modify Group Type
About: Active Directory

Changes a local group named Scientists to a global security group.

Const ADS_GROUP_TYPE_GLOBAL_GROUP = &h2
Const ADS_GROUP_TYPE_LOCAL_GROUP = &h4
Const ADS_GROUP_TYPE_UNIVERSAL_GROUP = &h8
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &h80000000
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.Put "groupType", _
    ADS_GROUP_TYPE_UNIVERSAL_GROUP + ADS_GROUP_TYPE_SECURITY_ENABLED
objGroup.SetInfo
Move a Group Within a Domain
About: Active Directory

Moves a group account from the HR OU to the Users container.

Set objOU = GetObject("LDAP://cn=Users,dc=NA,dc=fabrikam,dc=com")

objOU.MoveHere "LDAP://cn=atl-users,ou=HR,dc=NA,dc=fabrikam,dc=com", _
    vbNullString
Remove a User from a Group
About: Active Directory

Removes user MyerKen from the group Sea-Users.

Const ADS_PROPERTY_DELETE = 4 
 
Set objGroup = GetObject _
   ("LDAP://cn=Sea-Users,cn=Users,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.PutEx ADS_PROPERTY_DELETE, _
    "member",Array("cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objGroup.SetInfo
Remove All Group Memberships for a User Account
About: Active Directory

Removes the MyerKen user account from all Active Directory security groups.

On Error Resume Next

Const ADS_PROPERTY_DELETE = 4
Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com") 
arrMemberOf = objUser.GetEx("memberOf")
 
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "This account is not a member of any security groups."
    WScript.Quit
End If
 
For Each Group in arrMemberOf
    Set objGroup = GetObject("LDAP://" & Group) 
    objGroup.PutEx ADS_PROPERTY_DELETE, _
        "member", Array("cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
    objGroup.SetInfo
Next
Remove All the Members of a Group
About: Active Directory

Removes all the members of an Active Directory group named Sea-Users.

Const ADS_PROPERTY_CLEAR = 1 
 
Set objGroup = GetObject _
    ("LDAP://cn=Sea-Users,cn=Users,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.PutEx ADS_PROPERTY_CLEAR, "member", 0
objGroup.SetInfo
Remove the Manager of a Group
About: Active Directory

Removes the manager entry for the Active Directory security group named Scientists. When this script is run, the group will no longer have an assigned manager.

Const ADS_PROPERTY_CLEAR = 1 
 
Set objGroup = GetObject _
   ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com")

objGroup.PutEx ADS_PROPERTY_CLEAR, "managedBy", 0
objGroup.SetInfo
Replace Group Membership with All-New Members
About: Active Directory

Replaces the existing membership of a group named Scientists with two new group members: YoungRob and ShenAlan.

Const ADS_PROPERTY_UPDATE = 2 
 
Set objGroup = GetObject _
    ("LDAP://cn=Scientists,ou=R&D,dc=NA,dc=fabrikam,dc=com") 
 
objGroup.PutEx ADS_PROPERTY_UPDATE, "member", _
      Array("cn=YoungRob,ou=R&D,dc=NA,dc=fabrikam,dc=com", _
          "cn=ShenAlan,ou=R&D,dc=NA,dc=fabrikam,dc=com")
objGroup.SetInfo
Configure Trust Relationship Properties
About: Active Directory

Configures trust relationship refresh and validation properties.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")

Set colTrustList = objWMIService.ExecQuery _
    ("Select * from Microsoft_TrustProvider")

For Each objTrust in colTrustList
    objTrust.TrustListLifetime = 25
    objTrust.TrustStatusLifetime = 10
    objTrust.TrustCheckLevel = 1
    objTrust.Put_
Next
Install Active Directory Database Performance Counters
About: Active Directory

Installs the Active Database performance counters on a domain controller.

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
objFSO.CreateFolder ("C:\Performance")
Set objCopyFile = objFSO.GetFile("C:\windows\system32\esentprf.dll ")
objCopyFile.Copy ("C:\performance\esentprf.dll ") 

WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Open", _
        "OpenPerformanceData", "REG_SZ"
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Collect", _
        "CollectPerformanceData", "REG_SZ"
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Close", _
        "ClosePerformanceData", "REG_SZ"
WshShell.RegWrite _
    "HKLM\System\CurrentControlSet\Services\Esent\Performance\Library", _
        "C:\Performance\Esentprf.dll", "REG_SZ"
strCommandText = "%comspec% /c lodctr.exe c:\windows\system32\esentprf.ini" 
WshShell.Run strCommandText
List Active Directory Database Replication Partners
About: Active Directory

Configures trust relationship refresh and validation properties.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")

Set colReplicationOperations = objWMIService.ExecQuery _
    ("Select * from MSAD_ReplNeighbor")

For each objReplicationJob in colReplicationOperations 
    Wscript.Echo "Domain: " & objReplicationJob.Domain
    Wscript.Echo "Naming context DN: " & objReplicationJob.NamingContextDN
    Wscript.Echo "Source DSA DN: " & objReplicationJob.SourceDsaDN
    Wscript.Echo "Last synch result: " & objReplicationJob.LastSyncResult
    Wscript.Echo "Number of consecutive synchronization failures: " & _
        objReplicationJob.NumConsecutiveSyncFailures
Next
List Domain Information for Trust Partners
About: Active Directory

Returns local domain information.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")

Set colDomainInfo = objWMIService.ExecQuery _
    ("Select * from Microsoft_LocalDomainInfo")

For each objDomain in colDomainInfo
    Wscript.Echo "DNS name: " & objDomain.DNSName
    Wscript.Echo "Flat name: " & objDomain.FlatName
    Wscript.Echo "SID: " & objDomain.SID
    Wscript.Echo "Tree name: " & objDomain.TreeName
    Wscript.Echo "Domain controller name: " & objDomain.DCName
Next
List Trust Relationships
About: Active Directory

Enumerates trust relationships.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")

Set colTrustList = objWMIService.ExecQuery _
    ("Select * from Microsoft_DomainTrustStatus")

For each objTrust in colTrustList
    Wscript.Echo "Trusted domain: " & objTrust.TrustedDomain
    Wscript.Echo "Trust direction: " & objTrust.TrustDirection
    Wscript.Echo "Trust type: " & objTrust.TrustType
    Wscript.Echo "Trust attributes: " & objTrust.TrustAttributes
    Wscript.Echo "Trusted domain controller name: " & objTrust.TrustedDCName
    Wscript.Echo "Trust status: " & objTrust.TrustStatus
    Wscript.Echo "Trust is OK: " & objTrust.TrustIsOK
Next
Monitor Active Directory Database Performance
About: Active Directory

Uses cooked performance counters to monitor the performance of the Active Directory database on a domain controller.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colDatabases = objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_Esent_Database " _
        & "Where Name = 'NT Directory'")

For Each objADDatabase in colDatabases
    Wscript.Echo "Database cache hit percent: " & _
        objADDatabase.DatabaseCachePercentHit
Next
Monitor Active Directory Replication
About: Active Directory

Returns a list of pending replication jobs on a domain controller.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & _
        strComputer & "\root\MicrosoftActiveDirectory")

Set colReplicationOperations = objWMIService.ExecQuery _
        ("Select * from MSAD_ReplPendingOp")

If colReplicationOperations.Count = 0 Then
    Wscript.Echo "There are no replication jobs pending."
    Wscript.Quit
Else
    For each objReplicationJob in colReplicationOperations 
        Wscript.Echo "Serial number: " & objReplicationJob.SerialNumber
        Wscript.Echo "Time in queue: " & objReplicationJob.TimeEnqueued
        Wscript.Echo "DSA DN: " & objReplicationJob.DsaDN
        Wscript.Echo "DSA address: " & objReplicationJob.DsaAddress
        Wscript.Echo "Naming context DN: " & objReplicationJob.NamingContextDn
    Next
End If
Monitor Domain Controller Performance
About: Active Directory

Monitors the performance of an Active Directory domain controller.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colDatabases = objWMIService.ExecQuery _
    ("Select * from Win32_PerfFormattedData_NTDS_NTDS")

For Each objADDatabase in colDatabases
    Wscript.Echo "DS threads in use: " & objADDatabase.DSThreadsInUse
    Wscript.Echo "LDAP bind time: " & objADDatabase.LDAPBindTime
    Wscript.Echo "LDAP client sessions: " & objADDatabase.LDAPClientSessions
Next
Monitor FRS Replication
About: Active Directory

Uses cooked performance counters to monitor File Replication Service performance on a domain controller.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colFRSSet = objWMIService.ExecQuery _   
 ("Select * from Win32_PerfFormattedData_FileReplicaConn_FileReplicaConn")

For Each objFRSInstance in colFRSSet 
    Wscript.Echo "Remote change orders received: " & _
        objFRSInstance.RemoteChangeOrdersReceived
    Wscript.Echo "Remote change orders sent: " & _
        objFRSInstance.RemoteChangeOrdersSent
    Wscript.Echo "Packets sent: " & objFRSInstance.PacketsSent
Next
Monitor NTDS Performance
About: Active Directory

Uses cooked performance counters to monitor NTDS performance on a domain controller.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colItems = objRefresher.AddEnum _
    (objWMIService, "Win32_PerfFormattedData_NTDS_NTDS").objectSet
objRefresher.Refresh

For i = 1 to 5
    For Each objItem in colItems
    Wscript.Echo "Directory service threads in use: " & _
        objItem.DSThreadsInUse
    Wscript.Sleep 2000
    objRefresher.Refresh
    Next
Next
Assign a New Group Policy Link to an OU
About: Active Directory

Assigns the Group Policy link Sales Policy to the Sales OU in Active Directory.

On Error Resume Next

Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com") 
 
strExistingGPLink = objContainer.Get("gPLink")
 
strGPODisplayName = "Sales Policy"
strGPOLinkOptions = 2
strNewGPLink = "[" & GetGPOADsPath & ";" & strGPOLinkOptions & "]"
 
objContainer.Put "gPLink", strExistingGPLink & strNewGPLink
objContainer.Put "gPOptions", "0"
 
objContainer.SetInfo
 
Function GetGPOADsPath
    Set objConnection = CreateObject("ADODB.Connection")  
    objConnection.Open "Provider=ADsDSOObject;"   
 
    Set objCommand = CreateObject("ADODB.Command")
    objCommand.ActiveConnection = objConnection
 
    objCommand.CommandText = _
      ";;" & _
          "distinguishedName,displayName;onelevel"
    Set objRecordSet = objCommand.Execute
 
    Do Until objRecordSet.EOF
        If objRecordSet.Fields("displayName") = strGPODisplayName Then
          GetGPOADsPath = "LDAP://" & objRecordSet.Fields("distinguishedName")
          objConnection.Close
          Exit Function
        End If
        objRecordSet.MoveNext
    Loop
    objConnection.Close
End Function
Assign a New Manager to an OU
About: Active Directory

Assigns the user account AkersKim as manager of the Sales OU in Active Directory.

Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
objContainer.Put "managedBy", "cn=AkersKim,ou=Sales,dc=NA,dc=fabrikam,dc=com"
objContainer.SetInfo
Clear COM+ Attributes from a User Account
About: Active Directory

Removes all information from the msCOM-UserPartitionSetLink attribute of the MyerKen user account in Active Directory.

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

objUser.PutEx ADS_PROPERTY_CLEAR, "msCOM-UserPartitionSetLink", 0
objUser.SetInfo
Clear the COM+ Partition Link Set of an OU
About: Active Directory

Removes the COM+ partition link set assigned to the Sales OU in Active Directory.

Const ADS_PROPERTY_CLEAR = 1 

Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
objContainer.PutEx ADS_PROPERTY_CLEAR, "msCOM-UserPartitionSetLink", 0
objContainer.SetInfo
Clear the General Properties of an OU
About: Active Directory

Modifies the attribute values found on the General Properties page in Active Directory Users and Computers for an OU named Sales.

Const ADS_PROPERTY_CLEAR = 1 

Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
objContainer.PutEx ADS_PROPERTY_CLEAR, "description", 0
objContainer.PutEx ADS_PROPERTY_CLEAR, "street", 0
objContainer.PutEx ADS_PROPERTY_CLEAR, "l", 0
objContainer.PutEx ADS_PROPERTY_CLEAR, "st", 0
objContainer.PutEx ADS_PROPERTY_CLEAR, "postalCode", 0
objContainer.PutEx ADS_PROPERTY_CLEAR, "c", 0
objContainer.SetInfo
Clear the Group Policy Links Assigned to an OU
About: Active Directory

Removes all the Group Policy links assigned to the Sales OU in Active Directory.

Const ADS_PROPERTY_CLEAR = 1 
 
Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")

objContainer.PutEx ADS_PROPERTY_CLEAR, "gPLink", 0
objContainer.PutEx ADS_PROPERTY_CLEAR, "gPOptions", 0
objContainer.SetInfo
Create an OU
About: Active Directory

Creates a new organizational unit within Active Directory.

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

Set objOU = objDomain.Create("organizationalUnit", "ou=Management")
objOU.SetInfo
Create an OU in an Existing OU
About: Active Directory

Creates a new organizational unit (OU2) in an existing organizational unit (OU1).

Set objOU1 = GetObject("LDAP://ou=OU1,dc=na,dc=fabrikam,dc=com")

Set objOU2 = objOU1.Create("organizationalUnit", "ou=OU2")
objOU2.SetInfo
Delete an OU
About: Active Directory

Deletes an organizational unit named HR from the domain fabrikam.com.

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

objDomain.Delete "organizationalUnit", "ou=hr"
List COM+ Partition Information for a Domain
About: Active Directory

Returns COM+ partition information for the domain na.fabrikam.com.

Set objCOMPartitionSets = GetObject _
    ("LDAP://cn=ComPartitionSets,cn=System,dc=NA,dc=fabrikam,dc=com")
 
For Each objPartitionSet in objCOMPartitionSets
    WScript.Echo "Name: " & objPartitionSet.Name
Next
List COM+ Partition Sets
About: Active Directory

Returns a list of Active Directory COM+ partition sets.

Set objCOMPartitionSets = GetObject _
    ("LDAP://cn=ComPartitionSets,cn=System,dc=NA,dc=fabrikam,dc=com")
 
For Each objPartitionSet in objCOMPartitionSets
    WScript.Echo "Name: " & objPartitionSet.Name
Next
List Group Policy Information for an OU
About: Active Directory

Returns the values found on the Group Policy page in Active Directory Users and Computers for the Sales OU.

On Error Resume Next

Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
strGpLink = objContainer.Get("gPLink")
intGpOptions = objContainer.Get("gPOptions")
 
If strGpLink <> " " Then
    arrGpLinkItems = Split(strGpLink,"]")
    For i = UBound(arrGPLinkItems) to LBound(arrGpLinkItems) + 1 Step -1
        arrGPLink = Split(arrGpLinkItems(i-1),";")
        strDNGPLink = Mid(arrGPLink(0),9)
        WScript.Echo GetGPOName
        Select Case arrGPLink(1)
        Case 0
            WScript.Echo "No Override is cleared and the GPO is enabled."
        Case 1
            WScript.Echo "No Override is cleared and the GPO is disabled."
        Case 2
            WScript.Echo "No Override is checked and the GPO is enabled."
        Case 3
            WScript.Echo "No Override is checked and the GPO is disabled."
      End Select
    Next
    WScript.Echo VbCrLf
End If
 
If intGpOptions = 1 Then
    WScript.Echo "Block Policy Inheritance is checked."
Else
    WScript.Echo "Block Policy Inheritance is not checked."
End If
    
Function GetGPOName
    Set objConnection = CreateObject("ADODB.Connection")  
    objConnection.Open "Provider=ADsDSOObject;"   
 
    Set objCommand = CreateObject("ADODB.Command")
    objCommand.ActiveConnection = objConnection
 
    objCommand.CommandText = _
        ";;" & _
            "distinguishedName,displayName;onelevel"
    Set objRecordSet = objCommand.Execute
 
    Do Until objRecordSet.EOF
        If objRecordSet.Fields("distinguishedName") = strDNGPLink Then
            GetGPOName = objRecordSet.Fields("displayName")
            objConnection.Close
            Exit Function
      End If
      objRecordSet.MoveNext
    Loop
    objConnection.Close
End Function
List the Attributes of the organizationalUnit Class
About: Active Directory

Returns both the mandatory and optional attributes for the organizationalUnit class (as found in the Active Directory schema).

Set objOrganizationalUnitClass = _
    GetObject("LDAP://schema/organizationalUnit")

Set objSchemaClass = GetObject(objOrganizationalUnitClass.Parent)
 
i = 0
WScript.Echo "Mandatory attributes:"

For Each strAttribute in objOrganizationalUnitClass.MandatoryProperties
    i= i + 1
    WScript.Echo i & vbTab & strAttribute
    Set objAttribute = objSchemaClass.GetObject("Property",  strAttribute)
    WScript.Echo " (Syntax: " & objAttribute.Syntax & ")"
    If objAttribute.MultiValued Then
        WScript.Echo " Multivalued"
    Else
        WScript.Echo " Single-valued"
    End If
Next
 
WScript.Echo VbCrLf & "Optional attributes:"
For Each strAttribute in objOrganizationalUnitClass.OptionalProperties
    i= i + 1
    WScript.StdOut.Write i & vbTab & strAttribute
    Set objAttribute = objSchemaClass.GetObject("Property",  strAttribute)
    Wscript.Echo " [Syntax: " & objAttribute.Syntax & "]"
    If objAttribute.MultiValued Then
        WScript.Echo " Multivalued"
    Else
        WScript.Echo " Single-valued"
    End If
Next
List the COM+ Properties of an OU
About: Active Directory

Returns information about the COM+ properties configured for the Sales OU in Active Directory.

On Error Resume Next

Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
strMsCOMUserPartitionSetLink = objContainer.Get("msCOM-UserPartitionSetLink")
WScript.Echo "ms-COMUserPartitionSetLink: " & strMsCOMUserPartitionSetLink
List the General Properties of an OU
About: Active Directory

Returns information found on the General Properties page in Active Directory Users and Computers for an OU named Sales.

On Error Resume Next

Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
For Each strValue in objContainer.description
  WScript.Echo "Description: " & strValue
Next
 
Wscript.Echo "Street Address: " & strStreetAddress
Wscript.Echo "Locality: " & 
Wscript.Echo "State/porvince: " & objContainer.st
Wscript.Echo "Postal Code: " & objContainer.postalCode
Wscript.Echo "Country: " & objContainer.c
List the Managed By Information for an OU
About: Active Directory

Returns information about the account assigned as manager of the Sales OU in Active Directory.

On Error Resume Next
 
Set objContainer = GetObject _
   ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
strManagedBy = objContainer.Get("managedBy")
 
If IsEmpty(strManagedBy) = TRUE Then
    WScript.Echo "No user account is assigned to manage " & _
        "this OU."
Else
    Set objUser = GetObject("LDAP://" & strManagedBy)
    WScript.Echo "Manager: " & objUser.streetAddress
    WScript.Echo "Office: " & _
      objUser.physicalDeliveryOfficeName  
    WScript.Echo "Street Address: " & strStreetAddress
    WScript.Echo "Locality: " & objUser.l
    WScript.Echo "State/province: " & objUser.st
    WScript.Echo "Country: " & objUser.c
    WScript.Echo "Telephone Number: " & objUser.telephoneNumber
    WScript.Echo "Fax Number: " & _
      objUser.facsimileTelephoneNumber
End If
List the Owner of an OU
About: Active Directory

Returns the owner of the Sales OU in Active Directory.

Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
Set objNtSecurityDescriptor = objContainer.Get("ntSecurityDescriptor")
 
WScript.Echo "Owner Tab"
WScript.Echo "Current owner of this item: " & objNtSecurityDescriptor.Owner
List the Properties of an OU Object
About: Active Directory

Returns information found on the Object page in Active Directory Users and Computers for the Sales OU.

Set objContainer = GetObject _
   ("GC://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
strWhenCreated = objContainer.Get("whenCreated")
strWhenChanged = objContainer.Get("whenChanged")
 
Set objUSNChanged = objContainer.Get("uSNChanged")
dblUSNChanged = _
    Abs(objUSNChanged.HighPart * 2^32 + objUSNChanged.LowPart)
 
Set objUSNCreated = objContainer.Get("uSNCreated")
dblUSNCreated = _
    Abs(objUSNCreated.HighPart * 2^32 + objUSNCreated.LowPart)
 
objContainer.GetInfoEx Array("canonicalName"), 0
arrCanonicalName = objContainer.GetEx("canonicalName")
 
WScript.Echo "CanonicalName of object:"
For Each strValue in arrCanonicalName
    WScript.Echo vbTab & strValue
Next
WScript.Echo 
 
WScript.Echo "Object class: " & objContainer.Class & vbCrLf
WScript.Echo "whenCreated: " & strWhenCreated & " (Created - GMT)"
WScript.Echo "whenChanged: " & strWhenChanged & " (Modified - GMT)"
WScript.Echo VbCrLf
WScript.Echo "uSNChanged: " & dblUSNChanged & " (USN Current)"
WScript.Echo "uSNCreated: " & dblUSNCreated & " (USN Original)"
List the Security Descriptor for an OU
About: Active Directory

Returns the information found on the security descriptor for the Sales OU in Active Directory.

Const SE_DACL_PROTECTED = &H1000 
 
Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
Set objNtSecurityDescriptor = objContainer.Get("ntSecurityDescriptor")
 
intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
 
WScript.Echo "Permissions Tab"
strMessage = "Allow inheritable permissions from the parent to " & _
    "propogate to this object and all child objects "
If (intNtSecurityDescriptorControl And SE_DACL_PROTECTED) Then
    Wscript.Echo strMessage & "is disabled."
Else
    WScript.Echo strMessage & "is enabled."
End If
WScript.Echo 
 
Set objDiscretionaryAcl = objNtSecurityDescriptor.DiscretionaryAcl
DisplayAceInformation objDiscretionaryAcl, "DACL"
 
Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_ACCESS_ALLOWED = &H0 
    Const ADS_ACETYPE_ACCESS_DENIED = &H1 
    Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5 
    Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6 
    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            WScript.Echo strType & " permission entry: " & intAceCount
            WScript.Echo "Name: " & objAce.Trustee
 
            intAceType = objAce.AceType
            If (intAceType = ADS_ACETYPE_ACCESS_ALLOWED Or _
                intAceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT) Then
                WScript.Echo "Type: Allow Access"
            ElseIf (intAceType = ADS_ACETYPE_ACCESS_DENIED Or _
                intAceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) Then
                WScript.Echo "Type: Deny Acess"
            Else
                WScript.Echo "Acess Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            WScript.Echo VbCr
        End If
    Next
End Sub
 
Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100
 
    WScript.Echo VbCrLf & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        WScript.Echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        WScript.Echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        WScript.Echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        WScript.Echo vbTab & "-Modify owner."
  
    WScript.Echo VbCrLf & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
      WScript.Echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        WScript.Echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        WScript.Echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        WScript.Echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        WScript.Echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        WScript.Echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        WScript.Echo vbTab & "-List a tree of objects."
 
    WScript.Echo VbCrLf & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
          WScript.Echo "-None"
      Else 
      If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
          WScript.Echo vbTab & "-Extended access rights."
      If (AccessMask And ADS_RIGHT_DS_SELF) Then
          WScript.Echo vbTab & "-Active Directory must validate a property "
          WScript.Echo vbTab & " write operation beyond the schema definition "
          WScript.Echo vbTab & " for the attribute."
      End If
    End If
End Sub
List the System Access Control List of an OU
About: Active Directory

Returns information found on the System Access Control List (SACL) for the Sales OU in Active Directory.

Const SE_SACL_PROTECTED = &H2000 
Const ADS_SECURITY_INFO_OWNER = &H1 
Const ADS_SECURITY_INFO_GROUP = &H2
Const ADS_OPTION_SECURITY_MASK =&H3
Const ADS_SECURITY_INFO_DACL = &H4 
Const ADS_SECURITY_INFO_SACL = &H8
 
Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
objContainer.SetOption ADS_OPTION_SECURITY_MASK, ADS_SECURITY_INFO_OWNER _
    Or ADS_SECURITY_INFO_GROUP Or ADS_SECURITY_INFO_DACL _
    Or ADS_SECURITY_INFO_SACL
  
Set objNtSecurityDescriptor = objContainer.Get("ntSecurityDescriptor")
 
intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
 
WScript.Echo "Auditing Tab"
strMessage = "Allow inheritable auditing entries from" & _ 
    "the parent to propogate to this object and all child objects "
If (intNtSecurityDescriptorControl And SE_SACL_PROTECTED) Then
    Wscript.Echo strMessage & "is disabled."
Else
    WScript.Echo strMessage & "is enabled."
End If
WScript.Echo 
 
Set objSacl = objNtSecurityDescriptor.SystemAcl
DisplayAceInformation objSacl, "SACL"
 
Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_SYSTEM_AUDIT = &H2 
    Const ADS_ACETYPE_SYSTEM_AUDIT_OBJECT = &H7 
  
    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            WScript.Echo strType & " permission entry: " & intAceCount
            WScript.Echo "Name: " & objAce.Trustee
 
            intAceType = objAce.AceType
            WScript.Echo "ACETYPE IS: " & intAceType
            If (intAceType = ADS_ACETYPE_SYSTEM_AUDIT or _
                intAceType = ADS_ACETYPE_SYSTEM_AUDIT_OBJECT) Then
                WScript.StdOut.Write "Type: Success or Failure Audit"
            Else
                WScript.StdOut.Write "Audit Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            WScript.Echo 
        End If
    Next
End Sub
 
Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100
 
    WScript.Echo VbCrLf & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        WScript.Echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        WScript.Echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        WScript.Echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        WScript.Echo vbTab & "-Modify owner."
  
    WScript.Echo VbCrLf & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
        WScript.Echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        WScript.Echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        WScript.Echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        WScript.Echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        WScript.Echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        WScript.Echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        WScript.Echo vbTab & "-List a tree of objects."
 
    WScript.Echo VbCrLf & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
            WScript.Echo "-None"
    Else 
        If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
            WScript.Echo vbTab & "-Extended access rights."
        If (AccessMask And ADS_RIGHT_DS_SELF) Then
            WScript.Echo vbTab & "-Active Directory must validate a property "
            WScript.Echo vbTab & " write operation beyond the schema " & _
                "definition "
            WScript.Echo vbTab & " for the attribute."
        End If
    End If
End Sub
Modify the COM+ Partition Set Link of an OU
About: Active Directory

Assigns the COM+ partition set PartitionSet1 to the Sales OU in Active Directory.

Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
objContainer.Put "msCOM-UserPartitionSetLink", _
    "cn=PartitionSet1,cn=ComPartitionSets,cn=System,dc=NA,dc=fabrikam,dc=com"
objContainer.SetInfo
Modify the General Properties of an OU
About: Active Directory

Modifies the attribute values found on the General Properties page in Active Directory Users and Computers for an OU named Sales.

Const ADS_PROPERTY_UPDATE = 2

Set objContainer = GetObject _
    ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")
 
objContainer.Put "street", "Building 43" & vbCrLf & "One Microsoft Way"
objContainer.Put "l", "Redmond"
objContainer.Put "st", "Washington"
objContainer.Put "postalCode", "98053"
objContainer.Put "c", "US"
objContainer.PutEx ADS_PROPERTY_UPDATE, _
    "description", Array("Sales staff")
objContainer.SetInfo
Remove an OU Manager
About: Active Directory

Removes the manager entry for the Active Directory OU named Sales. When this group is run, the OU will no longer have an assigned manager.

Const ADS_PROPERTY_CLEAR = 1 
 
Set objContainer = GetObject _
  ("LDAP://ou=Sales,dc=NA,dc=fabrikam,dc=com")

objContainer.PutEx ADS_PROPERTY_CLEAR, "managedBy", 0
objContainer.SetInfo
Create an Active Directory Site
About: Active Directory

Creates an Active Directory site and sets the site link for the new site.

strSiteRDN      = "cn=Ga-Atl-Sales"
strSiteLinkRDN  = "cn=DEFAULTIPSITELINK"
strSiteLinkType = "IP"                      
 
Const ADS_PROPERTY_APPEND = 3
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
strSitesContainer = "LDAP://cn=Sites," & strConfigurationNC
 
Set objSitesContainer = GetObject(strSitesContainer)
 
Set objSite = objSitesContainer.Create("site", strSiteRDN)
objSite.SetInfo
 
Set objLicensingSiteSettings = objSite.Create("licensingSiteSettings", _
    "cn=Licensing Site Settings")
objLicensingSiteSettings.SetInfo
 
Set objNtdsSiteSettings = objSite.Create("nTDSSiteSettings", _
     "cn=NTDS Site Settings")
objNtdsSiteSettings.SetInfo
 
Set objServersContainer = objSite.Create("serversContainer", "cn=Servers")
objServersContainer.SetInfo
 
strSiteLinkPath = "LDAP://" & strSiteLinkRDN & ",cn=" & strSiteLinkType & _
    ",cn=Inter-Site Transports,cn=Sites," & strConfigurationNC
 
Set objSiteLink = GetObject(strSiteLinkPath)
objSiteLink.PutEx ADS_PROPERTY_APPEND, "siteList", _
                  Array(objSite.Get("distinguishedName"))
objSiteLink.SetInfo
Create an Active Directory Site Link
About: Active Directory

Creates an Active Directory site link.

strSite1Name    = "Ga-Atl-Sales"
strSite2Name    = "Wa-Red-Sales"
strSiteLinkRDN  = "cn=[" & strSite1Name & "][" & strSite2Name & "]"
intCost         = 100
intReplInterval = 60
strDescription  = "[" & strSite1Name & "][" & strSite2Name & "]"
 
Const ADS_PROPERTY_UPDATE = 2
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strSite1DN = "cn=" & strSite1Name & ",cn=Sites," & strConfigurationNC
strSite2DN = "cn=" & strSite2Name & ",cn=Sites," & strConfigurationNC
 
Set objInterSiteTransports = GetObject("LDAP://" & _
    "cn=IP,cn=Inter-Site Transports,cn=Sites," & strConfigurationNC)
 
Set objSiteLink = objInterSiteTransports.Create("siteLink", strSiteLinkRDN)
objSiteLink.Put "cost",         intCost
objSiteLink.Put "replInterval", intReplInterval
objSiteLink.Put "description",  strDescription

 
objSiteLink.PutEx ADS_PROPERTY_UPDATE, "siteList", _
                  Array(strSite1DN, strSite2DN)
objSiteLink.SetInfo
Create an Active Directory Subnet
About: Active Directory

Creates an Active Directory subnet.

strSubnetRDN     = "cn=192.168.1.0/26"
strSiteObjectRDN = "cn=Ga-Atl-Sales"
strDescription   = "192.168.1.0/255.255.255.192"
strLocation      = "USA/GA/Atlanta"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strSiteObjectDN = strSiteObjectRDN & ",cn=Sites," & strConfigurationNC
 
strSubnetsContainer = "LDAP://cn=Subnets,cn=Sites," & strConfigurationNC
 
Set objSubnetsContainer = GetObject(strSubnetsContainer)
 
Set objSubnet = objSubnetsContainer.Create("subnet", strSubnetRDN)
objSubnet.Put "siteObject", strSiteObjectDN
objSubnet.Put "description", strDescription

objSubnet.Put "location", strLocation
objSubnet.SetInfo
Delete an Active Directory Subnet
About: Active Directory

Deletes an Active Directory subnet.

strSubnetCN = "cn=192.168.1.0/26"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
strSubnetsContainer = "LDAP://cn=Subnets,cn=Sites," & strConfigurationNC
 
Set objSubnetsContainer = GetObject(strSubnetsContainer)
objSubnetsContainer.Delete "subnet", strSubnetCN
List Active Directory Connections
About: Active Directory

Lists Active Directory connections (nTDSConnection objects) for a specified domain controller.

strDcRDN   = "cn=atl-dc-01"
strSiteRDN = "cn=Ga-Atl-Sales"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strNtdsSettingsPath = "LDAP://cn=NTDS Settings," & strDcRDN & _
    ",cn=Servers," & strSiteRDN & ",cn=Sites," & strConfigurationNC
 
Set objNtdsSettings = GetObject(strNtdsSettingsPath)
 
objNtdsSettings.Filter = Array("nTDSConnection")
 
WScript.Echo strDcRDN & " NTDS Connection Objects" & vbCrLf & _
    String(Len(strDcRDN) + 24, "=")
 
For Each objConnection In objNtdsSettings
    WScript.Echo "Name:      " & objConnection.Name
    WScript.Echo "Enabled:   " & objConnection.enabledConnection
    WScript.Echo "From:      " & Split(objConnection.fromServer, ",")(1)
    WScript.Echo "Options:   " & objConnection.Options
    WScript.Echo "Transport: " & Split(objConnection.transportType, ",")(0)
    WScript.Echo "Naming Contexts"
    WScript.Echo "---------------"
    For Each objDNWithBin In objConnection.GetEx("ms-DS-ReplicatesNCReason")
        Wscript.Echo objDNWithBin.DNString
    Next
    WScript.Echo
Next
List Active Directory Sites
About: Active Directory

Lists Active Directory sites.

Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strSitesContainer = "LDAP://cn=Sites," & strConfigurationNC
Set objSitesContainer = GetObject(strSitesContainer)
objSitesContainer.Filter = Array("site")
 
For Each objSite In objSitesContainer
    WScript.Echo "Name: " & objSite.Name
Next
List All Domain Controllers
About: Active Directory

Returns a list of all the domain controllers in the fabrikam.com domain.

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCOmmand.ActiveConnection = objConnection
 
objCommand.CommandText = _
    "Select distinguishedName from " & _
        "'LDAP://cn=Configuration,DC=fabrikam,DC=com' " _
            & "where objectClass='nTDSDSA'" 
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
 
Do Until objRecordSet.EOF
    Wscript.Echo "Computer Name: " & _
        objRecordSet.Fields("distinguishedName").Value
    objRecordSet.MoveNext
Loop
List Servers in an Active Directory Site
About: Active Directory

Lists servers in a specified Active Directory site.

strSiteRDN = "cn=Ga-Atl-Sales"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strServersPath = "LDAP://cn=Servers," & strSiteRDN & ",cn=Sites," & _
    strConfigurationNC
Set objServersContainer = GetObject(strServersPath)
 
For Each objServer In objServersContainer
    WScript.Echo "Name: " & objServer.Name
Next
List the Protocols Over Which a Bridgehead Server Replicates
About: Active Directory

Reads the bridgehead transport list from a domain controller in a site.

On Error Resume Next
   
Set objServer = GetObject _
    ("LDAP://CN=SEA-DC-01,CN=Servers,CN=Default-First-Site-Name,"  & _
        " CN=Sites,CN=Configuration,DC=fabrikam,DC=com")
 
dnBHTList = objServer.GetEx("bridgeheadTransportList")
 
WScript.Echo "Bridge Head Transport List:"
WScript.Echo "This multi-valued attribute lists the protocol" & _
    "transports over which this BridgeHead Server replicates"
For Each dnValue in dnBHTList
    WScript.Echo "Value: " & dnValue
Next
List the Site Name for a Domain Controller
About: Active Directory

Reports the site name for a specified computer.

strDcName = "atl-dc-01"
Set objADSysInfo = CreateObject("ADSystemInfo")

strDcSiteName = objADSysInfo.GetDCSiteName(strDcName)
WScript.Echo "DC Site Name: " & strDcSiteName
List the Site Name for the Local Computer
About: Active Directory

Reports the site name for the local computer.

Set objADSysInfo = CreateObject("ADSystemInfo")

WScript.Echo "Current site name: " & objADSysInfo.SiteName
List the Subnets in all Active Directory Sites
About: Active Directory

Lists subnets in all Active Directory sites.

Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strSubnetsContainer = "LDAP://cn=Subnets,cn=Sites," & strConfigurationNC
 
Set objSubnetsContainer = GetObject(strSubnetsContainer)
 
objSubnetsContainer.Filter = Array("subnet")
 
Set objHash = CreateObject("Scripting.Dictionary")
 
For Each objSubnet In objSubnetsContainer
    objSubnet.GetInfoEx Array("siteObject"), 0
    strSiteObjectDN = objSubnet.Get("siteObject")
    strSiteObjectName = Split(Split(strSiteObjectDN, ",")(0), "=")(1)
 
    If objHash.Exists(strSiteObjectName) Then
        objHash(strSiteObjectName) = objHash(strSiteObjectName) & "," & _
            Split(objSubnet.Name, "=")(1)
    Else
        objHash.Add strSiteObjectName, Split(objSubnet.Name, "=")(1)
    End If
Next
 
For Each strKey In objHash.Keys
    WScript.Echo strKey & "," & objHash(strKey)
Next
List the Subnets in an Active Directory Site
About: Active Directory

Lists subnets in a specified Active Directory site.

strSiteRDN = "cn=Ga-Atl-Sales"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strSitePath = "LDAP://" & strSiteRDN & ",cn=Sites," & strConfigurationNC
 
Set objSite = GetObject(strSitePath)
 
objSite.GetInfoEx Array("siteObjectBL"), 0
arrSiteObjectBL = objSite.GetEx("siteObjectBL")
 
WScript.Echo strSiteRDN & " Subnets" & vbCrLf & _
    String(Len(strSiteRDN) + 8, "-")
 
For Each strSiteObjectBL In arrSiteObjectBL
    WScript.Echo Split(Split(strSiteObjectBL, ",")(0), "=")(1)
Next
List Your Domain Controller
About: Active Directory

Returns the name of the domain controller used to authenticate the logged-on user of a computer.

Set objDomain = GetObject("LDAP://rootDse")

objDC = objDomain.Get("dnsHostName")
Wscript.Echo "Authenticating domain controller:" & objDC
Move a Domain Controller to a New Active Directory Site
About: Active Directory

Moves a domain controller from one Active Directory site (strSourceSiteRDN) to another Active Directory site (strTargetSiteRDN).

strSourceSiteRDN = "cn=Default-First-Site-Name"
strTargetSiteRDN = "cn=Ga-Atl-Sales"
strDcRDN         = "cn=atl-dc-01"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strDcPath = "LDAP://" & strDcRDN & ",cn=Servers," & strSourceSiteRDN & _
    ",cn=Sites," & strConfigurationNC
 
strTargetSitePath = "LDAP://cn=Servers," & strTargetSiteRDN & _
    ",cn=Sites," & strConfigurationNC
 
Set objTargetSite = GetObject(strTargetSitePath)
objTargetSite.MoveHere strDcPath, strDcRDN
Rename an Active Directory Site
About: Active Directory

Renames an Active Directory site.

strOldSiteRDN = "cn=Default-First-Site-Name"
strNewSiteRDN = "cn=Ga-Atl-Sales"
 
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
 
strSitesContainer = "LDAP://cn=Sites," & strConfigurationNC
strOldSitePath = "LDAP://" & strOldSiteRDN & ",cn=Sites," & strConfigurationNC
 
Set objSitesContainer = GetObject(strSitesContainer)
objSitesContainer.MoveHere strOldSitePath, strNewSiteRDN
Verify that a Domain Controller is in a Site
About: Active Directory

Checks to see if a domain controller is in a specific Active Directory site.

strDcName = "atl-dc-01"
strSiteName = "ga-atl-sales"
 
Set objADSysInfo = CreateObject("ADSystemInfo")
strDcSiteName = objADSysInfo.GetDCSiteName(strDcName)
 
If UCase(strSiteName) = UCase(strDcSiteName) Then
    WScript.Echo "TRUE: " & strDcName & " is in site " & strSiteName
Else
    WScript.Echo "FALSE: " & strDcName & " is NOT in site " & strSiteName
End If
Add a Route to the Dial-In Properties of a User Account
About: Active Directory

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
Add Additional postOfficeBox Information for a User Account
About: Active Directory

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
Add an Additional Home Phone Number to a User Account
About: Active Directory

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 any 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
Add an Additional URL to a User Account
About: Active Directory

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
Assign the Primary Group for a User
About: Active Directory

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
Clearing User Account Address Attributes
About: Active Directory

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
Copy a Published Certificate to a User Account
About: Active Directory

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
Delete a Calling Station ID from a User Account
About: Active Directory

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
Delete a Post Office Box from a User Account
About: Active Directory

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
Delete Address Page Information for a User Account
About: Active Directory

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
Delete All Department and Direct Report Information from a User Account
About: Active Directory

Removes all information from the department, 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
Delete All Dial-In Properties for a User Account
About: Active Directory

Clears all Dial-In attribute values 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, "msNPAllowDialin", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msNPCallingStationID", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msNPSavedCallingStationID", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msRADIUSServiceType", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msRADIUSCallbackNumber", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msRASSavedCallbackNumber", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msRADIUSFramedIPAddress", 0
objUser.PutEx ADS_PROPERTY_CLEAR, "msRASSavedFramedIPAddress", 0 
objUser.PutEx ADS_PROPERTY_CLEAR, "msRADIUSFramedRoute", 0  
objUser.PutEx ADS_PROPERTY_CLEAR, "msRASSavedFramedRoute", 0
objUser.SetInfo
Delete All Published Certificates from a User Account
About: Active Directory

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
Delete an otherMobile Phone Number
About: Active Directory

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
Delete Published Certificates from a User Account
About: Active Directory

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
Delete Selected Attributes from a User Account
About: Active Directory

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
Delete Selected User Account Attributes
About: Active Directory

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
Delete User Account Telephone Attributes
About: Active Directory

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
Disable the Smartcard Required Attribute for a User Account
About: Active Directory

Disables the setting that requires 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
Enable a User to Log on at Any Time
About: Active Directory

Configures the MyerKen Active Directory user account so that the user can log on at any time on any day of the week.

Const ADS_PROPERTY_CLEAR = 1 

Set objUser = GetObject _
  ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
objUser.PutEx ADS_PROPERTY_CLEAR, "logonHours", 0
objUser.SetInfo
Modify Account Page Information for a User Account
About: Active Directory

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
Modify Address Page Information for a User Account
About: Active Directory

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
Modify COM+ Information for a User Account
About: Active Directory

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
Modify Dial-In Properties for a User Account
About: Active Directory

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
Modify General User Account Attributes
About: Active Directory

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
Modify Organization Properties for a User Account
About: Active Directory

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
Modify User Account Address Attributes
About: Active Directory

Configures address-related attributes for a user account.

Set objUser = GetObject _
    ("LDAP://cn=myerken,ou=management,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.Put "postOfficeBox", "2222"
objUser.SetInfo
Modify User Account General Properties
About: Active Directory

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"
objUser.SetInfo
Modify User Account Telephone Numbers
About: Active Directory

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
Modify User Profile Paths
About: Active Directory

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
Modify User Profile Properties
About: Active Directory

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
Modify User Telephone Properties
About: Active Directory

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
Require a User to Logon on Using a Smartcard
About: Active Directory

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
Assign a Password to a User
About: Active Directory

Configures a new password for a user.

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

objUser.SetPassword "i5A2sj*!"
Change the Password for a User
About: Active Directory

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"
Create a Non-Expiring Password
About: Active Directory

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
Enable Users to Change Their Passwords
About: Active Directory

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
List Domain Password Policy Settings
About: Active Directory

Displays password policy settings for the domain.

Const MIN_IN_DAY = 1440
Const 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
List Domain Password Property Attributes
About: Active Directory

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 "Password Properties = " & 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
List Password Attributes for a User Account
About: Active Directory

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
List When a Password Expires
About: Active Directory

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" &  _
                "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
List When a Password was Last Changed
About: Active Directory

Identifies the last time a user password was changed.

Set objUser = GetObject _
    ("LDAP://CN=myerken,OU=management,DC=Fabrikam,DC=com")

dtmValue = objUser.PasswordLastChanged
WScript.Echo "Password last changed: " & dtmValue
Prevent Passwords from Being Stored Using Reversible Encrypted Text
About: Active Directory

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
Prevent Users From Changing Their Passwords
About: Active Directory

Enables the User Cannot Change Password option, which prevents the user from changing his or her 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
Require Users to Change Their Password
About: Active Directory

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
Verify Whether Users Can Change Their Passwords
About: Active Directory

Identifies whether or not a user is allowed to change his or her 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

For Each Ace In objDACL
    If ((Ace.AceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) And _
        (LCase(Ace.ObjectType) = CHANGE_PASSWORD_GUID)) Then
            blnEnabled = True
    End If
Next

If blnEnabled Then
    WScript.Echo "The user cannot change his or her password."
Else
    WScript.Echo "The user can change his or her password."
End If
List Account Page Information for a User Account
About: Active Directory

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

On Error Resume Next

Set objUser = GetObject _
    ("LDAP://cn=Myerken,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
WScript.Echo "User Principal Name: " & objUser.userPrincipalName
WScript.Echo "SAM Account Name: " & objUser.sAMAccountName
WScript.Echo "User Workstations: " & objUser.userWorkstations

Set objDomain = GetObject("LDAP://dc=NA,dc=fabrikam,dc=com")
WScript.Echo "Domain controller: " & objDomain.dc
List Address Page Information for a User Account
About: Active Directory

Returns address-related attribute values for the MyerKen Active Directory user account.

On Error Resume Next
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
WScript.Echo "Street Address: " & objUser.streetAddress
WScript.Echo "Locality: " & objUser.l
WScript.Echo "State/province: " & objUser.st
WScript.Echo "Postal Code: " & objUser.postalCode
WScript.Echo "Country: " & objUser.c
 
WScript.Echo "Post Office Boxes:"
For Each strValue in objUser.postOfficeBox
    WScript.echo vbTab & vbTab & strValue
Next
List All Telephone Settings for a User Account
About: Active Directory

Displays all the telephone attribute values for the MyerKen Active Directory user account.

On Error Resume Next

Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
WScript.Echo "Home Phone: " & objUser.homePhone
WScript.Echo "Pager: " & objUser.pager
WScript.Echo "Mobile phone: " & objUser.mobile
WScript.Echo " IP Phone: " & objUser.ipPhone
WScript.Echo "Information: " & objUser.info
WScript.Echo " Fax Number: " & objUser.facsimileTelephoneNumber
 
WScript.Echo "Other Home Phone:"
For Each strValue in objUser.otherHomePhone
    WScript.Echo strValue
Next
 
WScript.Echo "Other Pager:"
For Each strValue in objUser.otherPager
    WScript.Echo strValue
Next
 
WScript.Echo "oOther Mobile Phone:"
For Each strValue in objUser.otherMobile
    WScript.Echo strValue
Next
 
WScript.Echo "Other IP Phone:"
For Each strValue in objUser.otherIpPhone
    WScript.Echo strValue
Next
 
WScript.Echo "Other Fax Number:"
For Each strValue in objUser.otherFacsimileTelephoneNumber
    WScript.Echo strValue
Next
List All the Attributes of the User Class
About: Active Directory

Returns a list of mandatory and optional attributes for the User class in Active Directory.

Set objUserClass = GetObject("LDAP://schema/user")
Set objSchemaClass = GetObject(objUserClass.Parent)
 
i = 0
WScript.Echo "Mandatory attributes:"
For Each strAttribute in objUserClass.MandatoryProperties
    i= i + 1
    WScript.Echo i & vbTab & strAttribute
    Set objAttribute = objSchemaClass.GetObject("Property",  strAttribute)
    WScript.Echo " (Syntax: " & objAttribute.Syntax & ")"
    If objAttribute.MultiValued Then
        WScript.Echo " Multivalued"
    Else
        WScript.Echo " Single-valued"
    End If
Next
 
WScript.Echo VbCrLf & "Optional attributes:"
For Each strAttribute in objUserClass.OptionalProperties
    i=i + 1
    WScript.Echo i & vbTab & strAttribute
    Set objAttribute = objSchemaClass.GetObject("Property",  strAttribute)
    WScript.Echo " [Syntax: " & objAttribute.Syntax & "]"
    If objAttribute.MultiValued Then
        WScript.Echo " Multivalued"
    Else
        WScript.Echo " Single-valued"
    End If
Next
List Allowed User Logon Hours
About: Active Directory

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
List Audit Permissions for a User Account
About: Active Directory

Returns audit permissions for the MyerKen Active Directory user account.

Const SE_SACL_PROTECTED = &H2000 
Const ADS_SECURITY_INFO_OWNER = &H1 
Const ADS_SECURITY_INFO_GROUP = &H2
Const ADS_OPTION_SECURITY_MASK =&H3
Const ADS_SECURITY_INFO_DACL = &H4 
Const ADS_SECURITY_INFO_SACL = &H8
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
objUser.SetOption ADS_OPTION_SECURITY_MASK, ADS_SECURITY_INFO_OWNER _
    Or ADS_SECURITY_INFO_GROUP Or ADS_SECURITY_INFO_DACL _
        Or ADS_SECURITY_INFO_SACL
  
Set objNtSecurityDescriptor = objUser.Get("ntSecurityDescriptor")
 
intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
 
WScript.Echo "Auditing Tab"
strMessage = "Allow inheritable auditing entries from" & _ 
    "the parent to propogate to this object and all child objects "
If (intNtSecurityDescriptorControl And SE_SACL_PROTECTED) Then
    Wscript.Echo strMessage & "is disabled."
Else
    WScript.Echo strMessage & "is enabled."
End If
WScript.Echo 
 
Set objSacl = objNtSecurityDescriptor.SystemAcl
DisplayAceInformation objSacl, "SACL"
 
Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_SYSTEM_AUDIT = &H2 
    Const ADS_ACETYPE_SYSTEM_AUDIT_OBJECT = &H7 
  
    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            WScript.Echo strType & " permission entry: " & intAceCount
            WScript.Echo "Name: " & objAce.Trustee
 
            intAceType = objAce.AceType
            WScript.Echo "ACETYPE IS: " & intAceType
            If (intAceType = ADS_ACETYPE_SYSTEM_AUDIT or _
                intAceType = ADS_ACETYPE_SYSTEM_AUDIT_OBJECT) Then
                WScript.Echo "Type: Success or Failure Audit"
            Else
                WScript.Echo "Audit Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            WScript.Echo 
        End If
    Next
End Sub
 
Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100
 
    WScript.Echo VbCrLf & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        WScript.Echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        WScript.Echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        WScript.Echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        WScript.Echo vbTab & "-Modify owner."
  
    WScript.Echo VbCrLf & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
        WScript.Echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        WScript.Echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        WScript.Echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        WScript.Echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        WScript.Echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        WScript.Echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        WScript.Echo vbTab & "-List a tree of objects."
 
    WScript.Echo VbCrLf & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
        WScript.Echo "-None"
    Else 
        If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
            WScript.Echo vbTab & "-Extended access rights."
            If (AccessMask And ADS_RIGHT_DS_SELF) Then
                WScript.Echo vbTab & "-Active Directory must validate " & _
                    "a property "
                WScript.Echo vbTab & " write operation beyond the " & _
                    "schema definition "
                WScript.Echo vbTab & " for the attribute."
        End If
    End If
End Sub
List COM+ Information for a User Account
About: Active Directory

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

On Error Resume Next

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

WScript.Echo "COM User Partition Set Link: " & _
    objUser.msCOM-UserPartitionSetLink
List Object Page Information for a User Account
About: Active Directory

Returns information about the MyerKen user account object in Active Directory.

Set objUser = GetObject _
    ("GC://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
strWhenCreated = objUser.Get("whenCreated")
strWhenChanged = objUser.Get("whenChanged")
 
Set objUSNChanged = objUser.Get("uSNChanged")
dblUSNChanged = _
    Abs(objUSNChanged.HighPart * 2^32 + objUSNChanged.LowPart)
 
Set objUSNCreated = objUser.Get("uSNCreated")
dblUSNCreated = _
    Abs(objUSNCreated.HighPart * 2^32 + objUSNCreated.LowPart)
 
objUser.GetInfoEx Array("canonicalName"), 0
arrCanonicalName = objUser.GetEx("canonicalName")
 
WScript.echo "Canonical Name of object:"
For Each strValue in arrCanonicalName
    WScript.Echo vbTab & strValue
Next
WScript.Echo 
 
WScript.Echo "Object class: " & objUser.Class
WScript.echo "When Created: " & strWhenCreated & " (Created - GMT)"
WScript.echo "When Changed: " & strWhenChanged & " (Modified - GMT)"
WScript.Echo 
WScript.Echo "USN Changed: " & dblUSNChanged & " (USN Current)"
WScript.Echo "USN Created: " & dblUSNCreated & " (USN Original)"
List Organization Information for a User Account
About: Active Directory

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")

WScript.Echo "Title: " & objUser.title
WScript.Echo "Department: " & objUser.department
WScript.Echo "Company: " & objUser.company
WScript.Echo "Manager: " & objUser.manager
 
For Each strValue in objUser.directReports
    WScript.Echo "Direct Reports: " & strValue
Next
List Published Certificates for a User Account
About: Active Directory

Retrieves a list of all the published certificates assigned to the MyerKen user account.

On Error Resume Next

Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D
Const ForWriting = 2
Const WshRunning = 0
 
Set objUser = GetObject _
    ("GC://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
objUser.GetInfoEx Array("userCertificate"), 0
arrUserCertificates = objUser.GetEx("userCertificate")
 
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "No assigned certificates"
    WScript.Quit
Else
    Set objShell = CreateObject("WScript.Shell")
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    strPath = "." 
    intFileCounter = 0
 
    For Each arrUserCertificate in arrUserCertificates
        strFileName = "file" & intFileCounter
        strFullName = objFSO.BuildPath(strPath, strFileName)
        Set objFile = objFSO.OpenTextFile(strFullName, ForWriting, True)
        
        For i = 1 To LenB(arrUserCertificate)
            ReDim Preserve arrUserCertificatesChar(i - 1)
            arrUserCertificatesChar(i-1) = _
                Hex(AscB(MidB(arrUserCertificate, i, 3)))
        Next
                
        intCounter=0
        For Each HexVal in arrUserCertificatesChar
            intCounter=intCounter + 1
            If Len(HexVal) = 1 Then 
                objFile.Write(0 & HexVal & " ")
            Else
                objFile.Write(HexVal & " ")
            End If
        Next
        objFile.Close
        Set objFile = Nothing
  
        Set objExecCmd1 = objShell.Exec _
            ("certutil -decodeHex " & strFileName & " " & strFileName & ".cer")
        Do While objExecCmd1.Status = WshRunning
            WScript.Sleep 100
        Loop
        Set objExecCmd1 = Nothing
 
        Set objExecCmd2 = objShell.Exec("certutil " & strFileName & ".cer")
        Set objStdOut = objExecCmd2.StdOut
        Set objExecCmd2 = Nothing
      
        WScript.Echo VbCrLf & "Certificate " & intFileCounter + 1
        While Not objStdOut.AtEndOfStream
            strLine = objStdOut.ReadLine
            If InStr(strLine, "Issuer:") Then
                WScript.Echo Trim(strLine)
                WScript.Echo vbTab & Trim(objStdOut.ReadLine)
            End If
            If InStr(strLine, "Subject:") Then
                Wscript.Echo Trim(strLine)
                WScript.Echo vbTab & Trim(objStdOut.ReadLine)
            End If
            If InStr(strLine, "NotAfter:") Then
                strLine = Trim(strLine)
                WScript.Echo "Expires:"
                Wscript.Echo vbTab & Mid(strLine, 11)
            End If
        Wend
 
        objFSO.DeleteFile(strFullName)
        objFSO.DeleteFile(strPath & "\" & strFileName & ".cer") 
  
        intFileCounter = intFileCounter + 1
    Next
End If
List Security Permissions for a User Account
About: Active Directory

Returns security permissions for the MyerKen Active Directory user account.

Const SE_DACL_PROTECTED = &H1000 
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
Set objNtSecurityDescriptor = objUser.Get("ntSecurityDescriptor")
intNtSecurityDescriptorControl = objNtSecurityDescriptor.Control
 
WScript.Echo "Permissions Tab"
strMessage = "Allow inheritable permissions from the parent to " & _
    "propogate to this object and all child objects "
If (intNtSecurityDescriptorControl And SE_DACL_PROTECTED) Then
    Wscript.Echo strMessage & "is disabled."
Else
    WScript.Echo strMessage & "is enabled."
End If
WScript.Echo 
 
Set objDiscretionaryAcl = objNtSecurityDescriptor.DiscretionaryAcl
DisplayAceInformation objDiscretionaryAcl, "DACL"
 
Sub DisplayAceInformation(SecurityStructure, strType)
    Const ADS_ACETYPE_ACCESS_ALLOWED = &H0 
    Const ADS_ACETYPE_ACCESS_DENIED = &H1 
    Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5 
    Const ADS_ACETYPE_ACCESS_DENIED_OBJECT = &H6 
    intAceCount = 0
    For Each objAce In SecurityStructure
        strTrustee = Mid(objAce.Trustee,1,12)
        If StrComp(strTrustee, "NT AUTHORITY", 1) <> 0 Then
            intAceCount = intAceCount + 1
            WScript.Echo strType & " permission entry: " & intAceCount
            WScript.Echo "Name: " & objAce.Trustee
 
            intAceType = objAce.AceType
            If (intAceType = ADS_ACETYPE_ACCESS_ALLOWED Or _
                intAceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT) Then
                WScript.Echo "Type: Allow Access"
            ElseIf (intAceType = ADS_ACETYPE_ACCESS_DENIED Or _
                intAceType = ADS_ACETYPE_ACCESS_DENIED_OBJECT) Then
                WScript.Echo "Type: Deny Acess"
            Else
                WScript.Echo "Acess Type Unknown."
            End If
            ReadBitsInAccessMask(objAce.AccessMask)
            WScript.Echo 
        End If
    Next
End Sub
 
Sub ReadBitsInAccessMask(AccessMask)
    Const ADS_RIGHT_DELETE = &H10000
    Const ADS_RIGHT_READ_CONTROL = &H20000
    Const ADS_RIGHT_WRITE_DAC = &H40000
    Const ADS_RIGHT_WRITE_OWNER = &H80000
    Const ADS_RIGHT_DS_CREATE_CHILD = &H1
    Const ADS_RIGHT_DS_DELETE_CHILD = &H2
    Const ADS_RIGHT_ACTRL_DS_LIST = &H4
    Const ADS_RIGHT_DS_SELF = &H8
    Const ADS_RIGHT_DS_READ_PROP = &H10
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_RIGHT_DS_DELETE_TREE = &H40
    Const ADS_RIGHT_DS_LIST_OBJECT = &H80
    Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100
 
    WScript.Echo VbCrLf & "Standard Access Rights"
    If (AccessMask And ADS_RIGHT_DELETE) Then _
        WScript.Echo vbTab & "-Delete an object."
    If (AccessMask And ADS_RIGHT_READ_CONTROL) Then _
        WScript.Echo vbTab & "-Read permissions."
    If (AccessMask And ADS_RIGHT_WRITE_DAC) Then _
        WScript.Echo vbTab & "-Write permissions."
    If (AccessMask And ADS_RIGHT_WRITE_OWNER) Then _
        WScript.Echo vbTab & "-Modify owner."
  
    WScript.Echo VbCrLf & "Directory Service Specific Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CREATE_CHILD) Then _
        WScript.Echo vbTab & "-Create child objects."
    If (AccessMask And ADS_RIGHT_DS_DELETE_CHILD) Then _
        WScript.Echo vbTab & "-Delete child objects."
    If (AccessMask And ADS_RIGHT_ACTRL_DS_LIST) Then _
        WScript.Echo vbTab & "-Enumerate an object."
    If (AccessMask And ADS_RIGHT_DS_READ_PROP) Then _
        WScript.Echo vbTab & "-Read the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_WRITE_PROP) Then _
        WScript.Echo vbTab & "-Write the properties of an object."
    If (AccessMask And ADS_RIGHT_DS_DELETE_TREE) Then _
        WScript.Echo vbTab & "-Delete a tree of objects"
    If (AccessMask And ADS_RIGHT_DS_LIST_OBJECT) Then _
        WScript.Echo vbTab & "-List a tree of objects."
 
    WScript.Echo VbCrLf & "Control Access Rights"
    If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) + _
        (AccessMask And ADS_RIGHT_DS_SELF) = 0 Then
            WScript.Echo "-None"
    Else 
        If (AccessMask And ADS_RIGHT_DS_CONTROL_ACCESS) Then _
            WScript.Echo vbTab & "-Extended access rights."
        If (AccessMask And ADS_RIGHT_DS_SELF) Then
            WScript.Echo vbTab & "-Active Directory must validate a property "
            WScript.Echo vbTab & " write operation beyond the schema " & _
                "definition "
            WScript.Echo vbTab & " for the attribute."
        End If
    End If
End Sub
List the Dial-In Property Configuration Settings for a User Account
About: Active Directory

Enumerates the Dial-In configuration settings for the MyerKen Active Directory user account.

On Error Resume Next

Const E_ADS_PROPERTY_NOT_FOUND  = &h8000500D

Const FourthOctet = 1
Const ThirdOctet = 256
Const SecondOctet = 65536
Const FirstOctet = 16777216
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
 
blnMsNPAllowDialin = objUser.Get("msNPAllowDialin")
WScript.Echo "Remote Access Permission (Dial-in or VPN)"
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "Control access through Remote Access Policy"
    Err.Clear
Else
    If blnMsNPAllowDialin = True Then
        WScript.Echo "Allow access (msNPAllowDialin)"
    Else
        WScript.Echo "Deny access (msNPAllowDialin)"
    End If
End If
WScript.Echo 
 
arrMsNPSavedCallingStationID = objUser.GetEx("msNPSavedCallingStationID")
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "No Caller-ID specified."
    Err.Clear
Else
    WScript.Echo "Verify Caller ID (msNPSavedCallingStationID): "
    For Each strValue in arrMsNPSavedCallingStationID
        WScript.echo strValue
    Next
  
    objUser.GetEx "msNPCallingStationID"
    If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
        WScript.Echo "Calling station ID(s) specified but not assigned."
        Err.Clear
    Else
        WScript.echo "Calling station ID(s) assigned."
    End If
  
End If
WScript.Echo 
 
intMsRADIUSServiceType = objUser.Get("msRADIUSServiceType")
WScript.Echo "Callback Options"
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "No Callback"
    Err.Clear
Else
    strMsRADIUSCallbackNumber = objUser.Get("msRADIUSCallbackNumber")
    If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
        WScript.Echo "Set by caller (Routing and Remote Access Service only)"
        Err.Clear
  
    strMsRASSavedCallbackNumber = objUser.Get("msRASSavedCallbackNumber")
    If Err.Number <> E_ADS_PROPERTY_NOT_FOUND Then
        WScript.Echo "Unused value of " & strMsRASSavedCallbackNumber & _
            " appears in the Always Callback to field."
    Else
        Err.Clear
    End If  
Else
    WScript.Echo "Always Callback to: " & _
        strMsRADIUSCallbackNumber & " (msRADIUSCallbackNumber)"
    End If
End If   
WScript.Echo
 
intMsRASSavedFramedIPAddress = objUser.Get("msRASSavedFramedIPAddress")
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "No static IP address assigned."
    Err.Clear
Else
    If sgn(intMsRASSavedFramedIPAddress) = -1 Then
        intIP = intMsRASSavedFramedIPAddress
        WScript.StdOut.Write 256 + (int(intIP/FirstOctet)) & "."
        intFirstRemainder = intIP mod FirstOctet
        WScript.StdOut.Write 256 + (int(intFirstRemainder/SecondOctet)) & "."
        intSecondRemainder = intFirstRemainder mod SecondOctet
        WScript.StdOut.Write 256 + (int(intSecondRemainder/ThirdOctet)) & "."
        intThirdRemainder = intSecondRemainder mod ThirdOctet
        WScript.Echo 256 + (int(intThirdRemainder/FourthOctet))
    Else
        intIP = intMsRASSavedFramedIPAddress
        WScript.StdOut.Write  int(intIP/FirstOctet) & "."
        intFirstRemainder = intIP mod FirstOctet
        WScript.StdOut.Write  int(intFirstRemainder/SecondOctet) & "."
        intSecondRemainder = intFirstRemainder mod SecondOctet
        WScript.StdOut.Write  int(intSecondRemainder/ThirdOctet) & "."
        intThirdRemainder = intSecondRemainder mod ThirdOctet
        WScript.Echo int(intThirdRemainder/FourthOctet)
    End If
    
    objUser.Get "msRADIUSFramedIPAddress"
    If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
        WScript.Echo "Static IP address specified but not assigned."
        Err.Clear
    Else
        WScript.Echo "Static IP Address assigned."
    End If
 
End If
WScript.Echo 
 
arrMsRASSavedFramedRoute = objUser.GetEx("msRASSavedFramedRoute")
If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
    WScript.Echo "No static Routes specified."
    Err.Clear
Else
    WScript.echo "Static Routes (msRASSavedFramedRoute):"
    WScript.Echo vbTab & "CIDR 0.0.0.0 Metric"
    For Each strValue in arrMsRASSavedFramedRoute
        WScript.echo vbTab & strValue
    Next
  
    objUser.GetEx "msRADIUSFramedRoute"
    If Err.Number = E_ADS_PROPERTY_NOT_FOUND Then
        WScript.Echo "Static Routes specified but not assigned."
        Err.Clear
    Else
        WScript.echo "Static Routes assigned."
    End If
End If
List User Account Account Page Properties
About: Active Directory

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")
 
WScript.Echo "User Principal Name: " & objUser.userPrincipalName
WScript.Echo "SAM Account Name: " & objUser.sAMAccountName
WScript.Echo "User Workstations: " & objUser.userWorkstations

Set objDomain = GetObject("LDAP://dc=fabrikam,dc=com")
WScript.Echo "Domain controller: " & objDomain.dc
List User Account Address Page Attributes
About: Active Directory

Retrieves user account attributes found on the Address 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")
 
WScript.Echo "Street Address: " & objUser.streetAddress
WScript.Echo "Post Office Box: " & objUser.postOfficeBox
WScript.Echo "Locality: " & objUser.l
WScript.Echo "Street: " & objUser.st
WScript.Echo "Postal Code: " & objUser.postalCode
WScript.Echo "Country: " & objUser.c
List User Account General Page Properties
About: Active Directory

Retrieves user account attributes found on the General Properties 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")


WScript.Echo "First Name: " & objUser.givenName
WScript.Echo "Initials: " & objUser.initials
WScript.Echo "Last Name: " & objUser.sn
WScript.Echo "Display Name: " & objUser.displayName
WScript.Echo "Office: " & _
    objUser.physicalDeliveryOfficeName
WScript.Echo "Telephone Number: " & objUser.telephoneNumber
WScript.Echo "Email: " & objUser.mail
WScript.Echo "Home Page: " & 
 
For Each strValue in objUser.description
    WScript.Echo "Description: " & strValue
Next

For Each strValue in objUser.otherTelephone
    WScript.Echo "Other Telephone: " & strValue
Next

For Each strValue in objUser.url
    WScript.Echo "URL: " & strValue
Next
List User Profile Properties
About: Active Directory

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")
 
Wscript.Echo "Profile Path: " & objUser.ProfilePath
Wscript.Echo "Script Path: " & objUser.ScriptPath
Wscript.Echo "Home Directory: " & objUser.HomeDirectory
Wscript.Echo "Home Drive: " & objUser.HomeDrive
List userAccountControl Values for an Active Directory User Account
About: Active Directory

Reads values from the userAccountControl of the MyerKen Active Directory user account.

Set objHash = CreateObject("Scripting.Dictionary")
 
objHash.Add "ADS_UF_SMARTCARD_REQUIRED", &h40000 
objHash.Add "ADS_UF_TRUSTED_FOR_DELEGATION", &h80000 
objHash.Add "ADS_UF_NOT_DELEGATED", &h100000 
objHash.Add "ADS_UF_USE_DES_KEY_ONLY", &h200000 
objHash.Add "ADS_UF_DONT_REQUIRE_PREAUTH", &h400000 
 
Set objUser = GetObject _
    ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
intUAC = objUser.Get("userAccountControl")
 
If objUser.IsAccountLocked = True Then
    Wscript.Echo "ADS_UF_LOCKOUT is enabled"
Else
    Wscript.Echo "ADS_UF_LOCKOUT is disabled"
End If
wscript.echo VBCRLF
 
For Each Key In objHash.Keys
    If objHash(Key) And intUAC Then 
        Wscript.Echo Key & " is enabled"
    Else
        Wscript.Echo Key & " is disabled"
  End If
Next
Search for a User Account in Active Directory
About: Active Directory

Searches Active Directory to see if a user account with the name kenmyer already exists.

strUserName = "kenmyer"
dtStart = TimeValue(Now())
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
 
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
 
objCommand.CommandText = _
    ";(&(objectCategory=User)" & _
         "(samAccountName=" & strUserName & "));samAccountName;subtree"
  
Set objRecordSet = objCommand.Execute
 
If objRecordset.RecordCount = 0 Then
    WScript.Echo "sAMAccountName: " & strUserName & " does not exist."
Else
    WScript.Echo strUserName & " exists."
End If
 
objConnection.Close
Copy a Published Certificate to a User Account
About: Active Directory

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
Copy Allowed Logon Hours from One Account to Another
About: Active Directory

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
Create 1000 Sample User Accounts
About: Active Directory

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."
Create a Contact in Active Directory
About: Active Directory

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

Set objOU = GetObject("LDAP://OU=management,dc=fabrikam,dc=com")

Set objUser = objOU.Create("contact", "cn=MyerKen")
objUser.SetInfo
Create a User Account
About: Active Directory

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
Create a User Account and Add it to a Group and an OU
About: Active Directory

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
Delete a User Account from Active Directory
About: Active Directory

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

Set objOU = GetObject("LDAP://ou=hr,dc=fabrikam,dc=com")

objOU.Delete "user", "cn=MyerKen"
List the Owner of a User Account
About: Active Directory

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
Modify the UPN Suffixes Defined in the Forest
About: Active Directory

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

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
Move a User Account
About: Active Directory

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
Move a User Account to a New Domain
About: Active Directory

Uses the MoveHere method to move a user account to another domain. Note that there are a number of restrictions associated with performing this type of move operation.

Set objOU = GetObject("LDAP://ou=management,dc=na,dc=fabrikam,dc=com")

objOU.MoveHere _
    "LDAP://cn=AckermanPilar,OU=management,dc=fabrikam,dc=com", vbNullString
Set a User Account So It Never Expires
About: Active Directory

Configures the MyerKen Active Directory user account so that it never expires. This is done by setting the expiration date to January 1, 1970.

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

objUser.AccountExpirationDate = "01/01/1970"
objUser.SetInfo
Disable a User Account
About: Active Directory

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
Enable a User Account
About: Active Directory

Enables a user account.

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

objUser.AccountDisabled = FALSE
objUser.SetInfo
List All the Disabled User Accounts in Active Directory
About: Active Directory

Returns a list of all disabled user accounts in the fabrikam.com domain.

Const ADS_UF_ACCOUNTDISABLE = 2
 
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    ";(objectCategory=User)" & _
        ";userAccountControl,distinguishedName;subtree"  
Set objRecordSet = objCommand.Execute
 
intCounter = 0
Do Until objRecordset.EOF
    intUAC=objRecordset.Fields("userAccountControl")
    If intUAC AND ADS_UF_ACCOUNTDISABLE Then
        WScript.echo objRecordset.Fields("distinguishedName") & " is disabled"
        intCounter = intCounter + 1
    End If
    objRecordset.MoveNext
Loop
 
WScript.Echo VbCrLf & "A total of " & intCounter & " accounts are disabled."
 
objConnection.Close
List the Date That a User Account Expires
About: Active Directory

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 date specified"
Else
    WScript.Echo "Account expiration date: " & objUser.AccountExpirationDate
End If
List the Status of a User
About: Active Directory

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
Modify the Expiration Date for a User Account
About: Active Directory

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

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

objUser.AccountExpirationDate = "03/30/2005"
objUser.SetInfo
Unlock a User Account
About: Active Directory

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
List Fax Server Activity Logging Options
About: Applications

Lists logging options for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objFaxLoggingOptions = objFaxServer.LoggingOptions
Set objFaxActivityLogging = objFaxLoggingOptions.ActivityLogging
Wscript.Echo "Database path: " & _
    objFaxActivityLogging.DatabasePath
Wscript.Echo "Log incoming: " & _
    objFaxActivityLogging.LogIncoming
Wscript.Echo "Log outgoing: " & _
    objFaxActivityLogging.LogOutgoing
List Fax Server Device Information
About: Applications

Lists device information for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set colDevices = objFaxServer.GetDevices()

For Each objFaxDevice in colDevices
    Wscript.Echo "ID: " & objFaxDevice.ID
    Wscript.Echo "CSID: " & objFaxDevice.CSID
    Wscript.Echo "Description: " & objFaxDevice.Description
    Wscript.Echo "Device name: " & objFaxDevice.DeviceName
    Wscript.Echo "Powered off: " & objFaxDevice.PoweredOff
    Wscript.Echo "Provider unique name: " & _
        objFaxDevice.ProviderUniqueName
    Wscript.Echo "Receive mode: " & objFaxDevice.ReceiveMode
    Wscript.Echo "Receiving now: " & objFaxDevice.ReceivingNow
    Wscript.Echo "Ringing now: " & objFaxDevice.RingingNow
    Wscript.Echo "Rings before answer: " & _
        objFaxDevice.RingsBeforeAnswer
    Wscript.Echo "Send enabled: " & objFaxDevice.SendEnabled
    Wscript.Echo "Sending now: " & objFaxDevice.SendingNow
    Wscript.Echo "TSID: " & objFaxDevice.TSID
Next
List Fax Server Device Providers
About: Applications

Lists all the device providers for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objDeviceProviders = objFaxServer.GetDeviceProviders

For Each objFaxDeviceProvider in objDeviceProviders
    Wscript.Echo "Debug: " & objFaxDeviceProvider.Debug
    Wscript.Echo "Friendly name: " & objFaxDeviceProvider.FriendlyName
    Wscript.Echo "Image name: " & objFaxDeviceProvider.ImageName
    Wscript.Echo "Initialization error code: " & _
        objFaxDeviceProvider.InitErrorCode
    Wscript.Echo "Major build: " & objFaxDeviceProvider.MajorBuild
    Wscript.Echo "Minor build: " & objFaxDeviceProvider.MinorBuild
    Wscript.Echo "Major version: " & objFaxDeviceProvider.MajorVersion
    Wscript.Echo "Minor version: " & objFaxDeviceProvider.MinorVersion
    Wscript.Echo "Status: " & objFaxDeviceProvider.Status
    Wscript.Echo "TAPI provider name: " & objFaxDeviceProvider.TAPIProviderName
    Wscript.Echo "Unique name: " & objFaxDeviceProvider.UniqueName
Next
List Fax Server Event Logging Options
About: Applications

Lists all the event logging options for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objFaxLoggingOptions = objFaxServer.LoggingOptions

Set objFaxEventLogging = objFaxLoggingOptions.EventLogging
Wscript.Echo "General events level: " & _
    objFaxEventLogging.GeneralEventsLevel
Wscript.Echo "Inbound events level: " & _
    objFaxEventLogging.InboundEventsLevel
Wscript.Echo "Initialization events level: " & _
    objFaxEventLogging.InitEventsLevel
Wscript.Echo "Outbound events level: " & _
    objFaxEventLogging.OutboundEventsLevel
List Fax Server Incoming Archive Information
About: Applications

Lists all the incoming archive information for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objFolder = objFaxServer.Folders

Set objIncomingArchive = objFolder.IncomingArchive
Wscript.Echo "Age limit: " & objIncomingArchive.AgeLimit
Wscript.Echo "Archive folder: " & objIncomingArchive.ArchiveFolder
Wscript.Echo "High quota watermark: " & objIncomingArchive.HighQuotaWatermark
Wscript.Echo "Low quota watermark: " & objIncomingArchive.LowQuotaWatermark
Wscript.Echo "Size low: " & objIncomingArchive.SizeLow
Wscript.Echo "Size high: " & objIncomingArchive.SizeHigh
Wscript.Echo "Size quota warning: " & objIncomingArchive.SizeQuotaWarning
Wscript.Echo "Use archive: " & objIncomingArchive.UseArchive
List Fax Server Incoming Queue Information
About: Applications

Indicates whether the incoming queue is blocked on the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objFolder = objFaxServer.Folders

Set objIncomingQueue = objFolder.IncomingQueue
Wscript.Echo "Blocked: " & objIncomingQueue.Blocked
List Fax Server Information
About: Applications

Returns information about the fax service installed in the computer atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Wscript.Echo "API version: " & objFaxServer.APIVersion
Wscript.Echo "Major build: " & objFaxServer.MajorBuild
Wscript.Echo "Minor build: " & objFaxServer.MinorBuild
Wscript.Echo "Major version: " & objFaxServer.MajorVersion
Wscript.Echo "Minor version: " & objFaxServer.MinorVersion
Wscript.Echo "Server name: " & objFaxServer.ServerName
List Fax Server Outgoing Archive Information
About: Applications

Lists all the outgoing archive information for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objFolder = objFaxServer.Folders
Set objOutgoingArchive = objFolder.OutgoingArchive

Wscript.Echo "Age limikt: " & objOutgoingArchive.AgeLimit
Wscript.Echo "Archive folder: " & objOutgoingArchive.ArchiveFolder
Wscript.Echo "High quota watermark: " & objOutgoingArchive.HighQuotaWatermark
Wscript.Echo "Low quota watermark: " & objOutgoingArchive.LowQuotaWatermark
Wscript.Echo "Size low: " & objOutgoingArchive.SizeLow
Wscript.Echo "Size high: " & objOutgoingArchive.SizeHigh
Wscript.Echo "Size quota warning: " & objOutgoingArchive.SizeQuotaWarning
Wscript.Echo "Use archive: " & objOutgoingArchive.UseArchive
List Fax Server Outgoing Queue Information
About: Applications

Lists all the outgoing queue information for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objFolder = objFaxServer.Folders
Set objOutgoingQueue = objFolder.OutgoingQueue

Wscript.Echo "Age limit: " & objOutgoingQueue.AgeLimit
Wscript.Echo "Allow personal cover pages: " & _
    objOutgoingQueue.AllowPersonalCoverPages
Wscript.Echo "Blocked: " & objOutgoingQueue.Blocked
Wscript.Echo "Branding: " & objOutgoingQueue.Branding
Wscript.Echo "Discount rate end: " & objOutgoingQueue.DiscountRateEnd
Wscript.Echo "Discount rate start: " & objOutgoingQueue.DiscountRateStart
Wscript.Echo "Paused: " & objOutgoingQueue.Paused
Wscript.Echo "Retries: " & objOutgoingQueue.Retries
Wscript.Echo "Retry delay: " & objOutgoingQueue.RetryDelay
Wscript.Echo "Use Device TSID: " & objOutgoingQueue.UseDeviceTSID
List Fax Server Receipt Options
About: Applications

Lists the receipt options for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objReceiptOptions = objFaxServer.ReceiptOptions

Wscript.Echo "Allowed receipts: " & _
    objReceiptOptions.AllowedReceipts
Wscript.Echo "Authentication type: " & _
    objReceiptOptions.AuthenticationType
Wscript.Echo "SMTP password: " & objReceiptOptions.SMTPPassword
Wscript.Echo "SMTP port: " & objReceiptOptions.SMTPPort
Wscript.Echo "SMTP sender: " & objReceiptOptions.SMTPSender
Wscript.Echo "SMTP server: " & objReceiptOptions.SMTPServer
Wscript.Echo "SMTP user: " & objReceiptOptions.SMTPUser
Wscript.Echo "Use for inbound routing: " & _
    objReceiptOptions.UseForInboundRouting
List Fax Server Security Information
About: Applications

Lists security information and granted rights for the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objSecurity = objFaxServer.Security

Wscript.Echo "Security descriptor: " & objSecurity.Descriptor
Wscript.Echo "Granted rights: " & objSecurity.GrantedRights
Wscript.Echo "Information type: " & objSecurity.InformationType
Monitor Fax Server Activity
About: Applications

Returns information about current activity on the fax server atl-dc-02.

Set objFaxServer = CreateObject("FaxComEx.FaxServer")
objFaxServer.Connect "atl-dc-02"

Set objfaxActivity = objFaxServer.Activity

Wscript.Echo "Incoming messages: " & objFaxActivity.IncomingMessages
Wscript.Echo "Outgoing messages: " & objFaxActivity.OutgoingMessages
Wscript.Echo "Queued messages: " & objFaxActivity.QueuedMessages
Wscript.Echo "Routing messages: " & objFaxActivity.RoutingMessages
Configuring the Indexing Service to Autostart
About: Applications

Configures the Indexing Service on the local computer to automatically start each time the computer starts. To configure the Indexing Service for manual start, set the parameter passed to the EnableCI method to False rather than True. Manual start is the default setting for the Indexing Service.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.EnableCI(True)
Create an Indexing Service Catalog
About: Applications

Adds an Indexing Service catalog named Script Catalog (with a catalog location of C:\Scripts) to the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.Stop()

Set objCatalog = objAdminIS.AddCatalog("Script Catalog","c:\scripts")
objAdminIS.Start()
Create an Indexing Service Scope
About: Applications

Adds a scope named Script Scope (with the path C:\Scripts) to an Indexing Service catalog named Script Catalog on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
Set objCatalog = objAdminIS.GetCatalogByName("Script Catalog")
Set objScope = objCatalog.AddScope("c:\scripts\Indexing Server", False)
objScope.Alias = "Script scope"
objScope.Path = "c:\scripts"
Delete an Indexing Service Catalog
About: Applications

Removes an Indexing Service catalog named Script Catalog from the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.Stop()
errResult = objAdminIS.RemoveCatalog("Script Catalog", True)
objAdminIS.Start()
Delete an Indexing Service Scope
About: Applications

Removes the Indexing Service scope C:\Scripts from the Indexing Service catalog named Script Catalog.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
Set objCatalog = objAdminIS.GetCatalogByName("Script Catalog")
objCatalog.RemoveScope("c:\scripts")
List Indexing Service Catalogs
About: Applications

Returns information about all the Indexing Service catalogs available on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objCatalog = objAdminIS.FindFirstCatalog()
If (objCatalog) Then
    Set objCatAdm = objAdminIS.GetCatalog()
    Wscript.Echo "Catalog location: " & objCatAdm.CatalogLocation
    Wscript.Echo "Catalog name: " & objCatAdm.CatalogName
    If (objAdminIS.IsRunning) Then 
        Wscript.Echo "Is stopped: " & objCatAdm.IsCatalogStopped
        Wscript.Echo "Is paused: " & objCatAdm.IsCatalogPaused
        Wscript.Echo "Is running: " & objCatAdm.IsCatalogRunning
        Wscript.Echo "Delayed filter count: " & objCatAdm.DelayedFilterCount
        Wscript.Echo "Documents to filter: " & objCatAdm.DocumentsToFilter
        Wscript.Echo "Filtered document count: " & _
            objCatAdm.FilteredDocumentCount
        Wscript.Echo "Fresh test count: " & objCatAdm.FreshTestCount
        Wscript.Echo "Index size: " & objCatAdm.IndexSize
        Wscript.Echo "Percent merge complete: " & objCatAdm.PctMergeComplete
        Wscript.Echo "Pending scan count: " & objCatAdm.PendingScanCount
        Wscript.Echo "Persistent index count: " & _
            objCatAdm.PersistentIndexCount
        Wscript.Echo "Query count: " & objCatAdm.QueryCount
        Wscript.Echo "State info: " & objCatAdm.StateInfo
        Wscript.Echo "Total document count: " & objCatAdm.TotalDocumentCount
        Wscript.Echo "Unique key count: " & objCatAdm.UniqueKeyCount
        Wscript.Echo "Word list count: " & objCatAdm.WordListCount
    End If 
End If
 
Do
    objCatalog = objAdminIS.FindNextCatalog()
    If (objCatalog) Then
        Set objCatAdm = objAdminIS.GetCatalog()
        Wscript.Echo "Catalog location: " & objCatAdm.CatalogLocation
        Wscript.Echo "Catalog name: " & objCatAdm.CatalogName
    If (objAdminIS.IsRunning) Then 
        Wscript.Echo "Is stopped: " & objCatAdm.IsCatalogStopped
        Wscript.Echo "Is paused: " & objCatAdm.IsCatalogPaused
        Wscript.Echo "Is running: " & objCatAdm.IsCatalogRunning
        Wscript.Echo "Delayed filter count: " & objCatAdm.DelayedFilterCount
        Wscript.Echo "Documents to filter: " & objCatAdm.DocumentsToFilter
        Wscript.Echo "Filtered document count: " & _
            objCatAdm.FilteredDocumentCount
        Wscript.Echo "Fresh test count: " & objCatAdm.FreshTestCount
        Wscript.Echo "Index size: " & objCatAdm.IndexSize
        Wscript.Echo "Percent merge complete: " & objCatAdm.PctMergeComplete
        Wscript.Echo "Pending scan count: " & objCatAdm.PendingScanCount
        Wscript.Echo "Persistent index count: " & _
            objCatAdm.PersistentIndexCount
        Wscript.Echo "Query count: " & objCatAdm.QueryCount
        Wscript.Echo "State info: " & objCatAdm.StateInfo
        Wscript.Echo "Total document count: " & objCatAdm.TotalDocumentCount
        Wscript.Echo "Unique key count: " & objCatAdm.UniqueKeyCount
        Wscript.Echo "Word list count: " & objCatAdm.WordListCount
        End If 
    Else
        Exit Do
   End If
Loop
List Indexing Service Scopes
About: Applications

Returns information about all the Indexing Service scopes found on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objCatalog = objAdminIS.FindFirstCatalog()
If (objCatalog) Then
    Set objCatAdm = objAdminIS.GetCatalog()
    Set objScopeAdm = objCatAdm.GetScope()
    Wscript.Echo "Alias: " & objScopeAdm.Alias
    Wscript.Echo "Exclude scope: " & objScopeAdm.ExcludeScope
    Wscript.Echo "Logon: " & objScopeAdm.Logon
    Wscript.Echo "Path: " & objScopeAdm.Path
    Wscript.Echo "Virtual scope: " & objScopeAdm.VirtualScope
End If
 
Do
    objCatalog = objAdminIS.FindNextCatalog()
    If (objCatalog) Then
        Set objCatAdm = objAdminIS.GetCatalog()
        Set objScopeAdm = objCatAdm.GetScope()
        Wscript.Echo "Alias: " & objScopeAdm.Alias
        Wscript.Echo "Exclude scope: " & objScopeAdm.ExcludeScope
        Wscript.Echo "Logon: " & objScopeAdm.Logon
        Wscript.Echo "Path: " & objScopeAdm.Path
        Wscript.Echo "Virtual scope: " & objScopeAdm.VirtualScope
    Else
        Exit Do
    End If
Loop
List Specific Files Included in the Indexing Service
About: Applications

Returns a list of all the files included in the Indexing Service catalog named Script Catalog.

On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString = "provider=msidxs;"
objConnection.Properties("Data Source") = "Script Catalog"
objConnection.Open
 
Set objCommand = CreateObject("ADODB.Command")
 
strQuery = "Select Filename from Scope()"
 
Set objRecordSet = objConnection.Execute(strQuery)
 
Do While Not objRecordSet.EOF
    Wscript.Echo objRecordSet("Filename")
    objRecordSet.MoveNext
Loop
List the State of the Indexing Service
About: Applications

Returns information about the current state of the Indexing Service on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
Wscript.Echo "Is running: " & objAdminIS.IsRunning
Wscript.Echo "Is paused: " & objAdminIS.IsPaused
Wscript.Echo "Computer name: " & objAdminIS.MachineName
Monitor Indexing Service Filter Performance
About: Applications

Uses cooked performance counters to return information about Indexing Service filter performance.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colItems = objRefresher.AddEnum(objWMIService, " & _
    "Win32_PerfFormattedData_ContentFilter_IndexingServiceFilter").objectSet
objRefresher.Refresh

For i = 1 to 5
    For Each objItem in colItems
        Wscript.Echo "Binding Time in Milliseconds: " & _
            objItem.Bindingtimemsec
        Wscript.Echo "Caption: " & objItem.Caption
        Wscript.Echo "Description: " & objItem.Description
        Wscript.Echo "Indexing Speed, Megabytes Per Hour: " & _
            objItem.IndexingspeedMBPerhr
        Wscript.Echo "Name: " & objItem.Name
        Wscript.Echo "Total Indexing Speed, Megabytes Per Hour: " & _
            objItem.TotalindexingspeedMBPerhr
        Wscript.Sleep 2000
        objRefresher.Refresh
    Next
Next
Monitor Indexing Service Performance
About: Applications

Uses cooked performance counters to return information about Indexing Service content index performance.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
Set colItems = objRefresher.AddEnum(objWMIService," & _
    "Win32_PerfFormattedData_ContentIndex_IndexingService").objectSet
objRefresher.Refresh

For i = 1 to 5
    For Each objItem in colItems
        Wscript.Echo "Caption: " & objItem.Caption
        Wscript.Echo "Deferred for Indexing: " & objItem.Deferredforindexing
        Wscript.Echo "Description: " & objItem.Description
        Wscript.Echo "Files to be Indexed: " & objItem.Filestobeindexed
        Wscript.Echo "Index Size in Megabytes: " & objItem.IndexsizeMB
        Wscript.Echo "Merge Progress: " & objItem.Mergeprogress
        Wscript.Echo "Name: " & objItem.Name
        Wscript.Echo "Number of Documents Indexed: " & _
            objItem.Numberdocumentsindexed
        Wscript.Echo "Running Queries: " & objItem.Runningqueries
        Wscript.Echo "Saved Indexes: " & objItem.Savedindexes
        Wscript.Echo "Total Number of Documents: " & _
            objItem.TotalNumberdocuments
        Wscript.Echo "Total Number of Queries: " & objItem.TotalNumberofqueries
        Wscript.Echo "Unique Keys: " & objItem.Uniquekeys
        Wscript.Echo "Word Lists: " & objItem.Wordlists
        Wscript.Sleep 2000
        objRefresher.Refresh
    Next
Next
Pause the Indexing Service
About: Applications

Pauses the Indexing Service on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.Pause()
Resume the Indexing Service
About: Applications

Resumes the Indexing Service on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.Continue()
Search for Files Using the Indexing Service
About: Applications

Returns the file name and file size for all files (recorded in the Script Catalog Indexing Service catalog) that contain the term Win32_NetworkAdapterConfiguration.

On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString = "provider=msidxs;"
objConnection.Properties("Data Source") = "Script Catalog"
objConnection.Open
 
Set objCommand = CreateObject("ADODB.Command")
 
strQuery = "Select Filename, Size, Contents from Scope() Where " _
    & "Contains('Win32_NetworkAdapterConfiguration')"
 
Set objRecordSet = objConnection.Execute(strQuery)
 
Do While Not objRecordSet.EOF
    Wscript.Echo objRecordSet("Filename"), objRecordSet("Size")
    objRecordSet.MoveNext
Loop
Search Indexing Server Using a Predefined Query
About: Applications

Uses the predefined query #AllProps to return the file name, file size, and author of all the files included in the Indexing Service catalog Script Catalog on the local computer.

On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString = "provider=msidxs;"
objConnection.Properties("Data Source") = "Script Catalog"
objConnection.Open
 
Set objCommand = CreateObject("ADODB.Command")
 
strQuery = "Create View #AllProps as Select * from Scope()"
 
Set objRecordSet = objConnection.Execute("Select * from Extended_FileInfo")
 
Do While Not objRecordSet.EOF
    Wscript.Echo objRecordSet("Filename") & ", " & objRecordSet("Size") & _
        ", " & objRecordSet("DocAuthor")
    objRecordSet.MoveNext
Loop
Search the Indexing Service Using a Free Text Search
About: Applications

Uses a free text search to return the file name and file size for all files in the Indexing Service catalog Script Catalog that include the term Win32_NetworkAdapterConfiguration.

On Error Resume Next

Set objConnection = CreateObject("ADODB.Connection")
objConnection.ConnectionString = "provider=msidxs;"
objConnection.Properties("Data Source") = "Script Catalog"
objConnection.Open
 
Set objCommand = CreateObject("ADODB.Command")
 
strQuery = "Select Filename, Size, Contents from Scope() Where " _
    & "Freetext('Win32_NetworkAdapterConfiguration')"
 
Set objRecordSet = objConnection.Execute(strQuery)
 
Do While Not objRecordSet.EOF
    Wscript.Echo objRecordSet("Filename"), objRecordSet("Size")
    objRecordSet.MoveNext
Loop
Start the Indexing Service
About: Applications

Starts the Indexing Service on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.Start()
Stop the Indexing Service
About: Applications

Stops the Indexing Service on the local computer.

On Error Resume Next

Set objAdminIS = CreateObject("Microsoft.ISAdm")
objAdminIS.Stop()
Delete Software
About: Applications

Uninstalls a hypothetical software program (Personnel database) installed using Windows Installer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery _
    ("Select * from Win32_Product Where Name = 'Personnel database'")

For Each objSoftware in colSoftware
    objSoftware.Uninstall()
Next
Install Software on a Remote Computer
About: Applications

Installs a hypothetical software program (using a Windows Installer package) on a remote computer. Requires delegation for the computer and user accounts involved in the procedure.

Const wbemImpersonationLevelDelegate = 4

Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objConnection = objwbemLocator.ConnectServer _
    ("WebServer", "root\cimv2", "fabrikam\administrator", _
         "password", , "kerberos:WebServer")
objConnection.Security_.ImpersonationLevel = wbemImpersonationLevelDelegate

Set objSoftware = objConnection.Get("Win32_Product")
errReturn = objSoftware.Install("\\atl-dc-02\scripts\1561_lab.msi",,True)
Install Software on the Local Computer
About: Applications

Installs a hypothetical software program (using a Windows Installer package) on a local computer.

Const ALL_USERS = True

Set objService = GetObject("winmgmts:")
Set objSoftware = objService.Get("Win32_Product")
errReturn = objSoftware.Install("c:\scripts\database.msi", , ALL_USERS)
List Information About the Binary Files Used by an Application
About: Applications

Returns the name and product code of binary information (such as bitmaps, icons, executable files, and so on) used by a Windows Installer application.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_Binary")

For Each objItem in colItems
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Product Code: " & objItem.ProductCode
    Wscript.Echo
Next
List Installed or Advertised Components and Applications
About: Applications

Returns a list of all Windows Installer components installed or advertised on a computer.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_ApplicationService")

For Each objItem in colItems
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Start Mode: " & objItem.StartMode
    Wscript.Echo
Next
List Installed Software
About: Applications

Returns a list of software that was installed on a computer using Windows Installer. This information is then written to a text file.

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("c:\scripts\software.tsv", True)

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
    ("Select * from Win32_Product")

objTextFile.WriteLine "Caption" & vbtab & _
    "Description" & vbtab & "Identifying Number" & vbtab & _
    "Install Date" & vbtab & "Install Location" & vbtab & _
    "Install State" & vbtab & "Name" & vbtab & _ 
    "Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
        & "Version" 

For Each objSoftware in colSoftware
    objTextFile.WriteLine objSoftware.Caption & vbtab & _
    objSoftware.Description & vbtab & _
    objSoftware.IdentifyingNumber & vbtab & _
    objSoftware.InstallDate2 & vbtab & _
    objSoftware.InstallLocation & vbtab & _
    objSoftware.InstallState & vbtab & _
    objSoftware.Name & vbtab & _
    objSoftware.PackageCache & vbtab & _
    objSoftware.SKUNumber & vbtab & _
    objSoftware.Vendor & vbtab & _
    objSoftware.Version
Next
objTextFile.Close
List Installed Software Features
About: Applications

Returns a list of features for all the software installed on a computer using Windows Installer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colFeatures = objWMIService.ExecQuery _
    ("Select * from Win32_SoftwareFeature")

For Each objFeature in colfeatures
    Wscript.Echo "Accesses: " & objFeature.Accesses
    Wscript.Echo "Attributes: " & objFeature.Attributes
    Wscript.Echo "Caption: " & objFeature.Caption
    Wscript.Echo "Description: " & objFeature.Description
    Wscript.Echo "Identifying Number: " & objFeature.IdentifyingNumber
    Wscript.Echo "Install Date: " & objFeature.InstallDate
    Wscript.Echo "Install State: " & objFeature.InstallState
    Wscript.Echo "Last Use: " & objFeature.LastUse
    Wscript.Echo "Name: " & objFeature.Name
    Wscript.Echo "Product Name: " & objFeature.ProductName
    Wscript.Echo "Vendor: " & objFeature.Vendor
    Wscript.Echo "Version: " & objFeature.Version
Next
List Microsoft Product IDs
About: Applications

Returns the Product IDs for Microsoft software products installed on a computer.

Set objMSInfo = CreateObject("MsPIDinfo.MsPID")
colMSApps = objMSInfo.GetPIDInfo()

For Each strApp in colMSApps
    Wscript.Echo strApp
Next
List the Codec Files on a Computer
About: Applications

Uses WMI to return information about all the audio and video codec files installed on a computer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_CodecFile")

For Each objItem in colItems
    Wscript.Echo "Access Mask: " & objItem.AccessMask
    Wscript.Echo "Archive: " & objItem.Archive
    Wscript.Echo "Caption: " & objItem.Caption
    strCreationDate = WMIDateStringToDate(objItem.CreationDate)
    Wscript.Echo "Creation Date: " & strCreationdate
    Wscript.Echo "Drive: " & objItem.Drive
    Wscript.Echo "Eight Dot Three File Name: " & _
        objItem.EightDotThreeFileName
    Wscript.Echo "Extension: " & objItem.Extension
    Wscript.Echo "File Name: " & objItem.FileName
    Wscript.Echo "File Size: " & objItem.FileSize
    Wscript.Echo "File Type: " & objItem.FileType
    Wscript.Echo "File System Name: " & objItem.FSName
    Wscript.Echo "Group: " & objItem.Group
    Wscript.Echo "Hidden: " & objItem.Hidden
    strInstallDate = WMIDateStringToDate(objItem.InstallDate)
    Wscript.Echo "Last Accessed: " & strLastAccessed
    strLastModified = WMIDateStringToDate(objItem.LastModified)
    Wscript.Echo "Last Modified: " & strLastModified
    Wscript.Echo "Manufacturer: " & objItem.Manufacturer
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Path: " & objItem.Path
    Wscript.Echo "Version: " & objItem.Version
Next
 
Function WMIDateStringToDate(dtmDate)
    WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
        Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
            & " " & Mid (dtmDate, 9, 2) & ":" & _
                Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate, _
                    13, 2))
End Function
Upgrade Software
About: Applications

Upgrades a hypothetical software program installed using Windows Installer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSoftware = objWMIService.ExecQuery _
    ("Select * from Win32__Product Where Name = 'Personnel Database'")

For Each objSoftware in colSoftware
    errReturn = objSoftware.Upgrade("c:\scripts\database2.msi")
Next
List Local Computer Information
About: Desktop Management

Uses the Shell object to return basic configuration information for the local computer.

Set objComputer = CreateObject("Shell.LocalMachine")

Wscript.Echo "Computer name: " & objComputer.MachineName
Wscript.Echo "Shutdown allowed: " & objComputer.IsShutdownAllowed
Wscript.Echo "Friendly UI enabled: " & objComputer.IsFriendlyUIEnabled
Wscript.Echo "Guest access mode: " & objComputer.IsGuestAccessMode
Wscript.Echo "Guest account enabled: " & _
    objComputer.IsGuestEnabled(0)
Wscript.Echo "Multiple users enabled: " & _
    objComputer.IsMultipleUsersEnabled
Wscript.Echo "Offline files enabled: " & _
    objComputer.IsOfflineFilesEnabled
Wscript.Echo "Remote connections enabled: " & _
    objComputer.IsRemoteConnectionsEnabled
Wscript.Echo "Undock enabled: " & objComputer.IsUndockEnabled
Verify That SQL Server is Installed on a Computer
About: Desktop Management

Indicates whether SQL Server is running on a computer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where Name = 'MSSQLServer'")

If colServices.Count > 0 Then
    For Each objService in colServices
        Wscript.Echo "SQL Server is " & objService.State & "."
    Next
Else
    Wscript.Echo "SQL Server is not installed on this computer."
End If
Verify Whether Internet Explorer Enhanced Security is Enabled for the Logged-on User
About: Desktop Management

Indicates whether Internet Explorer Enhanced Security (IE hardening) is enabled for the current user of a computer.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."
Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet " _
    & "Settings\ZoneMap"
strValueName = "IEHarden"
objReg.GetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,intHarden
 
If intHarden = 1 Then
    Wscript.Echo "IE hardening is turned on for the current user."
Else
    Wscript.Echo "IE hardening is not turned on for the current user."
End If
Add a Web Site to the Favorites Menu
About: Desktop Management

Adds a shortcut to msdn.microsoft.com to the Internet Favorites folder.

Const ADMINISTRATIVE_TOOLS = 6

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ADMINISTRATIVE_TOOLS) 
Set objFolderItem = objFolder.Self     

Set objShell = WScript.CreateObject("WScript.Shell")
strDesktopFld = objFolderItem.Path
Set objURLShortcut = objShell.CreateShortcut(strDesktopFld & "\MSDN.url")
objURLShortcut.TargetPath = "http://msdn.microsoft.com"
objURLShortcut.Save
Add Sites to an Internet Explorer Security Zone
About: Desktop Management

Adds the Web site Contoso.com to the Trusted sites zone and BenefitsWeb to the Local intranet zone on a computer running Internet Explorer Enhanced Security Configuration.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."
Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "ZoneMap\ESCDomains\Contoso.com"
objReg.CreateKey HKEY_CURRENT_USER,strKeyPath
strValueName = "http"
dwValue = 2
objReg.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "ZoneMap\ESCDomains\BenefitsWeb"
objReg.CreateKey HKEY_CURRENT_USER,strKeyPath
strValueName = "*"
dwValue = 1
objReg.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
Delete a Site from an Internet Explorer Security Zone
About: Desktop Management

Deletes the site Contoso.com from an Internet Explorer security zone.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."
Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "ZoneMap\ESCDomains\Contoso.com"
objReg.DeleteKey HKEY_CURRENT_USER, strKeyPath
Delete an Allowed Protocol from an Internet Explorer Security Zone Site
About: Desktop Management

Deletes the http protocol from the Finance site in an Internet Explorer security zone.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."

Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "ZoneMap\ESCDomains\Finance"
strDWORDValueName = "http"

objReg.DeleteValue HKEY_CURRENT_USER,strKeyPath,strDWORDValueName
List Internet Explorer Connection Summary Information
About: Desktop Management

Returns basic connection information (including whether HTTP 1.1 has been enabled) for Internet Explorer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_ConnectionSummary")

For Each strIESetting in colIESettings
    Wscript.Echo "Connection preference: " & _
        strIESetting.ConnectionPreference
    Wscript.Echo "HTTP 1.1. enabled: " & strIESetting.EnableHTTP11
    Wscript.Echo "Proxy HTTP 1.1. enabled: " & strIESetting.ProxyHTTP11
Next
List Audited Internet Explorer Events from the Security Log
About: Desktop Management

Retrieves audited Internet Explorer events from the Security event log.

On Error Resume Next

strComputer = "."
Set dtmDate = CreateObject("WbemScripting.SWbemDateTime")
Set objWMIService = GetObject("winmgmts:" _
    & "{(Security)}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
        ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security' AND " _
            & "EventCode = '560'")

For Each objEvent in colLoggedEvents
    errResult = _
        InStr(objEvent.Message,"\REGISTRY\MACHINE\SOFTWARE\Microsoft\") 
    If errResult <> 0 Then
        Select Case objEvent.EventType
            Case 4 strEventType = "Success"
            Case 5 strEventType = "Failure"
        End Select
        Wscript.Echo objEvent.User
        dtmDate.Value = objEvent.TimeWritten
        dtmTimeWritten = dtmDate.GetVarDate
        Wscript.Echo "Time written: " & dtmTimeWritten
        Wscript.Echo strEventType
        Wscript.Echo "Record number: " & objEvent.RecordNumber & VbCrLf
        Wscript.Echo objEvent.Message
        Wscript.Echo 
    End If
Next
List Internet Explorer Cache Settings
About: Desktop Management

Returns configuration settings for the Internet Explorer cache.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_Cache")

For Each strIESetting in colIESettings
    Wscript.Echo "Page refresh type: " & strIESetting.PageRefreshType
    Wscript.Echo "Temporary Internet files folder: " & _
        strIESetting.TempInternetFilesFolder
Next
List Internet Explorer COM Object Settings
About: Desktop Management

Returns basic COM class information for Internet Explorer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_Object")

For Each strIESetting in colIESettings
    Wscript.Echo "Code base: " & strIESetting.CodeBase
    Wscript.Echo "Program file: " & strIESetting.ProgramFile
    Wscript.Echo "Status: " & strIESetting.Status
Next
List Internet Explorer Connection Settings
About: Desktop Management

Returns information about Internet Explorer connection settings.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_ConnectionSettings")

For Each strIESetting in colIESettings
    Wscript.Echo "Allow Internet programs: " & _
        strIESetting.AllowInternetPrograms
    Wscript.Echo "Autoconfiguration URL: " & strIESetting.AutoConfigURL
    Wscript.Echo "Auto disconnect: " & strIESetting.AutoDisconnect
    Wscript.Echo "Autoconfiguration proxy detection mode: " & _
        strIESetting.AutoProxyDetectMode
    Wscript.Echo "Data encryption: " & strIESetting.DataEncryption
    Wscript.Echo "Default: " & strIESetting.Default
    Wscript.Echo "Default gateway: " & strIESetting.DefaultGateway
    Wscript.Echo "Dialup server: " & strIESetting.DialUpServer
    Wscript.Echo "Disconnect idle time: " & strIESetting.DisconnectIdleTime
    Wscript.Echo "Encrypted password: " & strIESetting.EncryptedPassword
    Wscript.Echo "IP address: " & strIESetting.IPAddress
    Wscript.Echo "IP header compression: " & _
        strIESetting.IPHeaderCompression
    Wscript.Echo "Modem: " & strIESetting.Modem
    Wscript.Echo "Name: " & strIESetting.Name
    Wscript.Echo "Network logon: " & strIESetting.NetworkLogon
    Wscript.Echo "Network protocols: " & strIESetting.NetworkProtocols
    Wscript.Echo "Primary DNS server: " & strIESetting.PrimaryDNS
    Wscript.Echo "Primary WINS server: " & strIESetting.PrimaryWINS
    Wscript.Echo "Proxy: " & strIESetting.Proxy
    Wscript.Echo "Proxy override: " & strIESetting.ProxyOverride
    Wscript.Echo "Proxy server: " & strIESetting.ProxyServer
    Wscript.Echo "Redial attempts: " & strIESetting.RedialAttempts
    Wscript.Echo "Redial wait: " & strIESetting.RedialWait
    Wscript.Echo "Script fileame: " & strIESetting.ScriptFileName
    Wscript.Echo "Secondary DNS server: " & strIESetting.SecondaryDNS
    Wscript.Echo "Secondary WINS server: " & strIESetting.SecondaryWINS
    Wscript.Echo "Server assigned IP address: " & _
        strIESetting.ServerAssignedIPAddress
    Wscript.Echo "Server assigned name server: " & _
        strIESetting.ServerAssignedNameServer
    Wscript.Echo "Software compression: " & strIESetting.SoftwareCompression
Next
List Internet Explorer File Version Information
About: Desktop Management

Returns basic file version information for Internet Explorer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_FileVersion")

For Each strIESetting in colIESettings
    Wscript.Echo "Company: " & strIESetting.Company
    Wscript.Echo "Date: " & strIESetting.Date
    Wscript.Echo "File name: " & strIESetting.File
    Wscript.Echo "Path: " & strIESetting.Path
    Wscript.Echo "File size: " & strIESetting.Size
    Wscript.Echo "Version: " & strIESetting.Version
Next
List Internet Explorer LAN Settings
About: Desktop Management

Returns network information (including proxy server information) for Internet Explorer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_LANSettings")

For Each strIESetting in colIESettings
    Wscript.Echo "Autoconfiguration proxy: " & strIESetting.AutoConfigProxy
    Wscript.Echo "Autoconfiguration URL: " & strIESetting.AutoConfigURL
    Wscript.Echo "Autoconfiguration Proxy detection mode: " & _
        strIESetting.AutoProxyDetectMode
    Wscript.Echo "Proxy: " & strIESetting.Proxy
    Wscript.Echo "Proxy override: " & strIESetting.ProxyOverride
    Wscript.Echo "Proxy server: " & strIESetting.ProxyServer
Next
List Internet Explorer Security Setting Values
About: Desktop Management

Demonstration script that indicates whether scripting is enabled in the Internet Explorer Local Intranet zone.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."
strEntry = "1400"

Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "Zones\1"
objReg.GetDWORDValue HKEY_CURRENT_USER, strKeyPath, strEntry, dwValue

Select Case dwValue
    Case 0 strSetting = "Enabled"
    Case 1 strSetting = "Prompt"
    case 3 strSetting = "Disabled"
End Select

Wscript.Echo "Allow scripting: " & strSetting
List Internet Explorer Security Zone Settings
About: Desktop Management

Retrieves the current setting level for each Internet Explorer security zone.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_Security")

For Each strIESetting in colIESettings
    Wscript.Echo "Zone name: " & strIESetting.Zone
    Wscript.Echo "Security level: " & strIESetting.Level
Next
List Internet Explorer Summary Settings
About: Desktop Management

Returns basic information (including version number and build number) for Internet Explorer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\root\cimv2\Applications\MicrosoftIE")

Set colIESettings = objWMIService.ExecQuery _
    ("Select * from MicrosoftIE_Summary")

For Each strIESetting in colIESettings
    Wscript.Echo "Active printer: " & strIESetting.ActivePrinter
    Wscript.Echo "Build: " & strIESetting.Build
    Wscript.Echo "Cipher strength: " & strIESetting.CipherStrength
    Wscript.Echo "Content advisor: " & strIESetting.ContentAdvisor
    Wscript.Echo "IE Administration Kit installed: " & _
        strIESetting.IEAKInstall
    Wscript.Echo "Language: " & strIESetting.Language
    Wscript.Echo "Name: " & strIESetting.Name
    Wscript.Echo "Path: " & strIESetting.Path
    Wscript.Echo "Product ID: " & strIESetting.ProductID
    Wscript.Echo "Version: " & strIESetting.Version
Next
List Sites in Internet Explorer Security Zones
About: Desktop Management

Lists all the sites in the Internet Explorer security zones on a computer running IE Enhanced Security Configuration.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."

Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "ZoneMap\ESCDomains"
objReg.EnumKey HKEY_CURRENT_USER, strKeyPath, arrSubKeys

For Each subkey In arrSubKeys
    strNewPath = strKeyPath & "\" & subkey
    ShowSubkeys
Next

Sub ShowSubkeys
    arrPath = Split(strNewPath, "\")
    intSiteName = Ubound(arrPath)
    strSiteName = arrPath(intSiteName)
    objReg.EnumValues HKEY_CURRENT_USER, strNewPath, arrEntries, arrValueTypes

    If Not IsArray(arrEntries) Then
        arrPath = Split(strNewPath, "\")
        intSiteName = Ubound(arrPath)
        strSiteName = arrPath(intSiteName)
        Wscript.Echo strsitename
            objReg.EnumKey HKEY_CURRENT_USER, strNewPath, arrSubKeys2

        For Each subkey In arrSubKeys2
            strNewPath2 = strNewPath & "\" & subkey
            arrPath = Split(strNewPath2, "\")
            intSiteName = Ubound(arrPath)
            strSiteName = arrPath(intSiteName)
            objReg.EnumValues HKEY_CURRENT_USER, strNewPath2, arrEntries2,_
                arrValueTypes

            For i = 0 to Ubound(arrEntries2)
                objReg.GetDWORDValue HKEY_CURRENT_USER, strNewPath2, _
                    arrEntries2(i),dwValue
            Next

            Select Case dwValue
                Case 0 strZone = "My Computer"
                Case 1 strZone = "Local Intranet zone"
                Case 2 strZone = "Trusted Sites Zone"
                Case 3 strZone = "Internet Zone"
                Case 4 strZone = "Restricted Sites Zone"   
            End Select

            Wscript.Echo vbtab & strSiteName & " -- " & strZone
       Next
    End If

    For i = 0 to Ubound(arrEntries)
        objReg.GetDWORDValue HKEY_CURRENT_USER, strNewPath, _
            arrEntries(i),dwValue
    Next
        
    Select Case dwValue
        Case 0 strZone = "My Computer"
        Case 1 strZone = "Local Intranet zone"
        Case 2 strZone = "Trusted Sites Zone"
        Case 3 strZone = "Internet Zone"
        Case 4 strZone = "Restricted Sites Zone"   
    End Select

    Wscript.Echo strSiteName & " -- " & strZone

End Sub
Modify Advanced Internet Explorer Settings
About: Desktop Management

Demonstration script that disables the Download Complete message box that typically appears after downloading a file using Internet Explorer.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."
strValue = "no"

Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Internet Explorer\Main"
objReg.SetStringValue HKEY_CURRENT_USER, strKeyPath, _
    "NotifyDownloadComplete",strValue
Modify Internet Explorer Advanced Settings
About: Desktop Management

Demonstration script that indicates whether the Internet Explorer Enhanced Security Configuration dialog box is displayed each time IE starts.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."
strEntry = "DisplayTrustAlertDlg"

Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Internet Explorer\Main"
objReg.GetDWORDValue HKEY_CURRENT_USER, strKeyPath, strEntry ,dwValue

If dwValue = 1 Then
    Wscript.Echo "Enhanced security dialog box is displayed." 
Else
    Wscript.Echo "Enhanced security dialog box is not displayed." 
End If
Modify Internet Explorer Security Settings
About: Desktop Management

Demonstration script that enables scripting for sites in the Internet Explorer Local Intranet zone.

On Error Resume Next

Const HKEY_CURRENT_USER = &H80000001

strComputer = "."

Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\" _
    & "Zones\1"
strEntryName = "1400"
dwvalue = 0
objReg.SetDWORDValue HKEY_CURRENT_USER, strKeyPath, strEntryName,dwValue
Monitor Internet Explorer Security Changes
About: Desktop Management

Issues an alert any time an audited Internet Explorer setting is changed and recorded in the Security event log.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{"{impersonationLevel=impersonate,(Security)}!\\" & strComputer & _
        "\root\cimv2")

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _    
    ("SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA " _
        & "'Win32_NTLogEvent' AND TargetInstance.EventCode = '560' AND " _
            & "TargetInstance.Logfile = 'Security' GROUP WITHIN 2")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
        strAlertToSend = "Internet Explorer security settings have been " & _
            "changed."
        Wscript.Echo strAlertToSend
Loop
Verify Internet Explorer Enhanced Security Configuration Status
About: Desktop Management

Reports the status of Internet Explorer Enhanced Security Configuration on a computer.

On Error Resume Next

Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set objReg = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}\\" & strComputer & _
        "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Active Setup\Installed Components\" _
    & "{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
strValueName = "IsInstalled"
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,intAdmin
 
strKeyPath = "SOFTWARE\Microsoft\Active Setup\Installed Components\" _
    & "{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"
strValueName = "IsInstalled"
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,intUsers

strConfiguration = intAdmin & intUsers
Select Case strConfiguration
    Case "00"
        Wscript.Echo "The use of Internet Explorer is not restricted on " _
            & "this server."
    Case "01"
        Wscript.Echo "The use of Internet Explorer is restricted for the " _
           & "administrators group on this server. The use of Internet " _
           & "Explorer is not restricted for any other user group."
    Case "10"
        Wscript.Echo "The use of Internet Explorer is not restricted for the" _
            & " administrators group on this server. The use of Internet " _
            & "Explorer is restricted for any other user group."
    Case "11"
        Wscript.Echo "The use of Internet Explorer is restricted for all " _
            & "user groups on this server."
End Select
List Logon Session Information
About: Desktop Management

Returns information about logon sessions associated with the user currently logged on to a computer.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_LogonSession")

For Each objItem in colItems
    Wscript.Echo "Authentication Package: " & objItem.AuthenticationPackage
    Wscript.Echo "Logon ID: " & objItem.LogonId
    Wscript.Echo "Logon Type: " & objItem.LogonType
    Wscript.Echo "Start Time: " & objItem.StartTime
    Wscript.Echo
Next
List the User Logged on to a Remote Computer
About: Desktop Management

Returns the user name of the user currently logged on to a remote computer. To use this script, replace atl-ws-01 with the name of the remote computer you want to check. Although this script will run on Windows NT 4.0, Windows 98, and Windows 2000, it will not always return information.

strComputer = "atl-ws-o1"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 

Set colComputer = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
 
For Each objComputer in colComputer
    Wscript.Echo "Logged-on user: " & objComputer.UserName
Next
List User Passport Information
About: Desktop Management

Returns information about the .NET passport for the user currently logged-on to a computer.

Set objUser = CreateObject("UserAccounts.PassportManager")
Wscript.Echo "Current Passport: " & objUser.CurrentPassport
Wscript.Echo "Member services URL: " & objUser.MemberServicesURL
List Items in the Administrative Tools Folder
About: Desktop Management

Reports the path to the Administrative Tools folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const ADMINISTRATIVE_TOOLS = &H2f&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ADMINISTRATIVE_TOOLS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the All Users Application Data Folder
About: Desktop Management

Reports the path to the All Users Application Data folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const ALL_USERS_APPLICATION_DATA = &H23&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ALL_USERS_APPLICATION_DATA)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the All Users Desktop Folder
About: Desktop Management

Reports the path to the All Users Desktop folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const ALL_USERS_DESKTOP = &H19&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ALL_USERS_DESKTOP)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the All Users Programs Folder
About: Desktop Management

Reports the path to the All Users Programs folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const ALL_USERS_PROGRAMS = &H17&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ALL_USERS_PROGRAMS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the All Users Start Menu Folder
About: Desktop Management

Reports the path to the All Users Start Menu folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const ALL_USERS_START_MENU = &H16&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ALL_USERS_START_MENU)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the All Users Startup Folder
About: Desktop Management

Reports the path to the All Users Startup folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const ALL_USERS_STARTUP = &H18&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ALL_USERS_STARTUP)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Application Data Folder
About: Desktop Management

Reports the path to the Application Data folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const APPLICATION_DATA = &H1a&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(APPLICATION_DATA)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Common Files Folder
About: Desktop Management

Reports the path to the Common Files folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const COMMON_FILES = &H2b&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(COMMON_FILES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Control Panel Folder
About: Desktop Management

Reports the path to the Windows Control Panel, and then lists the individual applications installed. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const CONTROL_PANEL = &H3&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(CONTROL_PANEL)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Desktop Folder
About: Desktop Management

Reports the path to the Desktop folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const DESKTOP = &H10&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(DESKTOP)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Fonts Folder
About: Desktop Management

Reports the path to the Fonts folder, and then lists any fonts found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const FONTS = &H14&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(FONTS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Internet Cookies Folder
About: Desktop Management

Reports the path to the Internet Cookies folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const COOKIES = &H21&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(COOKIES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Internet Favorites Folder
About: Desktop Management

Reports the path to the Internet Favorites folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const FAVORITES = &H6&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(FAVORITES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Local Application Data Folder
About: Desktop Management

Reports the path to the Local Application Data folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const LOCAL_APPLICATION_DATA = &H1c&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(LOCAL_APPLICATION_DATA)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the My Computer Folder
About: Desktop Management

Reports the path to My Computer, and then lists any items found there. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const MY_COMPUTER = &H11&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_COMPUTER)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the My Documents Folder
About: Desktop Management

Reports the path to the My Documents folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const MY_DOCUMENTS = &H5&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_DOCUMENTS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the My Music Folder
About: Desktop Management

Reports the path to the My Music folder, and then lists any items found in that folder.

Const MY_MUSIC = &Hd&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_MUSIC)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the My Network Places Folder
About: Desktop Management

Reports the path to the My network Places folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const MY_NETWORK_PLACES = &H12&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_NETWORK_PLACES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the My Videos Folder
About: Desktop Management

Reports the path to the My Videos folder, and then lists any items found in that folder.

Const MY_VIDEOS = &He&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_VIDEOS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Network Connections Folder
About: Desktop Management

Reports the path to the Network Connections folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const NETWORK_CONNECTIONS = &H31&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Print Neighborhood Folder
About: Desktop Management

Reports the path to the Print Neighborhood folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const PRINTHOOD = &H1b&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(PRINTHOOD)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Printers and Faxes Folder
About: Desktop Management

Reports the path to the Printers and Faxes folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const PRINTERS_AND_FAXES = &H4&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(PRINTERS_AND_FAXES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Program Files Folder
About: Desktop Management

Reports the path to the Program Files folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const PROGRAM_FILES = &H26&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(PROGRAM_FILES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Programs Folder
About: Desktop Management

Reports the path to the Recycle Bin, and then lists any items found there. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const PROGRAMS = &H2&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(PROGRAMS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Recycle Bin Folder
About: Desktop Management

Reports the path to the Recycle Bin, and then lists any items found there. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const RECYCLE_BIN = &Ha&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(RECYCLE_BIN)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the SendTo Folder
About: Desktop Management

Reports the path to the SendTo folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const SENDTO = &H9&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(SENDTO)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Start Menu Folder
About: Desktop Management

Reports the path to the Start Menu folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const START_MENU = &Hb&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(START_MENU)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Startup Folder
About: Desktop Management

Reports the path to the Startup folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const STARTUP = &H7&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(STARTUP)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the System32 Folder
About: Desktop Management

Reports the path to the System32 folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const SYSTEM32 = &H25&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(SYSTEM32)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Templates Folder
About: Desktop Management

Reports the path to the Templates folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const TEMPLATES = &H15&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(TEMPLATES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Temporary Internet Files Folder
About: Desktop Management

Reports the path to the Temporary Internet Files folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const TEMPORARY_INTERNET_FILES = &H20&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(TEMPORARY_INTERNET_FILES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the User Profile Folder
About: Desktop Management

Reports the path to the logged-on user's User Profiles folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const USER_PROFILE = &H28&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(USER_PROFILE)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List Items in the Windows Folder
About: Desktop Management

Reports the path to the Windows folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const WINDOWS = &H24&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(WINDOWS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List the Items in the Internet Explorer History Folder
About: Desktop Management

Reports the path to the Internet Explorer History folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const LOCAL_SETTINGS_HISTORY = &H22&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(LOCAL_SETTINGS_HISTORY)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List the Items in the My Pictures Folder
About: Desktop Management

Reports the path to the My Pictures folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const MY_PICTURES = &H27&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_PICTURES)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List the Items in the My Recent Documents Folder
About: Desktop Management

Reports the path to the My Recent Documents folder, and then lists any items found in that folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const MY_RECENT_DOCUMENTS = &H8&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(MY_RECENT_DOCUMENTS)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List the Items in the Network Neighborhood Folder
About: Desktop Management

Reports the path to the Network Neighborhood, and then lists any items found there. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const NETHOOD = &H13&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETHOOD)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path

Set colItems = objFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
Next
List the Path to the Internet Explorer Folder
About: Desktop Management

Reports the path to the Internet Explorer special folder. For Windows NT 4.0 and Windows 98, this script requires Windows Script Host 5.1 and Internet Explorer 4.0 or later.

Const INTERNET_EXPLORER = &H1&

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(INTERNET_EXPLORER)
Set objFolderItem = objFolder.Self
Wscript.Echo objFolderItem.Path
List Computer Startup Commands
About: Desktop Management

Enumerates all startup commands on a computer, including those found in the Startup folder and those found in the Registry.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_StartupCommand")

For Each objStartupCommand in colStartupCommands
    Wscript.Echo "Command: " & objStartupCommand.Command
    Wscript.Echo "Description: " & objStartupCommand.Description
    Wscript.Echo "Location: " & objStartupCommand.Location
    Wscript.Echo "Name: " & objStartupCommand.Name
    Wscript.Echo "Setting ID: " & objStartupCommand.SettingID
    Wscript.Echo "User: " & objStartupCommand.User
Next
List Computer Startup Options
About: Desktop Management

Returns a list of startup options for a computer, including the startup delay time and other information found in Boot.ini.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

For Each objStartupCommand in colStartupCommands
    Wscript.Echo "Reset Boot Enabled: " & _
        objStartupCommand.AutomaticResetBootOption
    Wscript.Echo "Reset Boot Possible: " & _
        objStartupCommand.AutomaticResetCapability
    Wscript.Echo "Boot State: " & objStartupCommand.BootupState
    Wscript.Echo "Startup Delay: " & objStartupCommand.SystemStartupDelay
    For i = 0 to Ubound(objStartupCommand.SystemStartupOptions)
        Wscript.Echo "Startup Options: " & _
            objStartupCommand.SystemStartupOptions(i)
    Next
    Wscript.Echo "Startup Setting: " & _
        objStartupCommand.SystemStartupSetting
Next
List Recovery Configuration Options
About: Desktop Management

Returns a list of settings that indicate the action to be taken by a computer should a stop event (blue screen) occur.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colRecoveryOptions = objWMIService.ExecQuery _
    ("Select * from Win32_OSRecoveryConfiguration")

For Each objOption in colRecoveryOptions 
    Wscript.Echo "Auto reboot: " & objOption.AutoReboot
    Wscript.Echo "Debug File Path: " & objOption.DebugFilePath
    Wscript.Echo "Debug Info Type: " & objOption.DebugInfoType
    Wscript.Echo "Kernel Dump Only: " & objOption.KernelDumpOnly
    Wscript.Echo "Name: " & objOption.Name
    Wscript.Echo "Overwrite Existing Debug File: " & _
        objOption.OverwriteExistingDebugFile
    Wscript.Echo "Send Administrative Alert: " & objOption.SendAdminAlert
    Wscript.Echo "Write Debug Information: " & objOption.WriteDebugInfo
    Wscript.Echo "Write to System Log: " & objOption.WriteToSystemLog
Next
List the Boot Configuration Properties of a Computer
About: Desktop Management

Returns boot configuration information for a computer.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_BootConfiguration")

For Each objItem in colItems
    Wscript.Echo "Boot Directory: " & objItem.BootDirectory
    Wscript.Echo "Configuration Path: " & objItem.ConfigurationPath
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "Last Drive: " & objItem.LastDrive
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Scratch Directory: " & objItem.ScratchDirectory
    Wscript.Echo "Setting ID: " & objItem.SettingID
    Wscript.Echo "Temp Directory: " & objItem.TempDirectory
Next
Modify Recovery Configuration Options
About: Desktop Management

Configures a computer to do a complete memory dump to the file C:\Scripts\memory.dmp should a stop event (blue screen) occur.

Const COMPLETE_MEMORY_DUMP = 1

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colRecoveryOptions = objWMIService.ExecQuery _
    ("Select * from Win32_OSRecoveryConfiguration")

For Each objOption in colRecoveryOptions 
    objOption.DebugInfoType = COMPLETE_MEMORY_DUMP
    objOption.DebugFilePath = "c:\scripts\memory.dmp"
    objOption.OverWriteExistingDebugFile = False
    objOption.Put_
Next
Modify System Startup Delay
About: Desktop Management

Configures a computer to wait 10 seconds (instead of the default 30 seconds) before automatically loading the default operating system upon startup.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colStartupCommands = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

For Each objStartupCommand in colStartupCommands
    objStartupCommand.SystemStartupDelay = 10
    objStartupCommand.Put_
Next
Restart a Computer
About: Desktop Management

Restarts a computer.

strComputer = "atl-dc-01"
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate,(Shutdown)}!\\" & _
        strComputer & "\root\cimv2")

Set colOperatingSystems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")

For Each objOperatingSystem in colOperatingSystems
    objOperatingSystem.Reboot()
Next
Shut Down a Computer
About: Desktop Management

Shuts down a computer.

strComputer = "."
Set objWMIService = GetObject_
    ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\" & _
        strComputer & "\root\cimv2")

Set colOperating Systems = objWMIService.ExecQuery _
    ("Select * from Win32_OperatingSystem")
 
For Each objOperatingSystem in colOperatingSystems
    objOperatingSystem.Win32Shutdown(1)
Next
Conduct a System Restore
About: Desktop Management

Performs a system restore on a computer using system restore point No. 20. To perform a system restore using a different system restore point, simply change the value of the constant RESTORE_POINT.

Const RESTORE_POINT = 20
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objItem = objWMIService.Get("SystemRestore")
errResults = objItem.Restore(RESTORE_POINT)
Create a System Restore Point
About: Desktop Management

Creates a new system restore point on a computer, specifying that the restore point was created prior to installing a new device driver.

CONST DEVICE_DRIVER_INSTALL = 10
CONST BEGIN_SYSTEM_CHANGE = 100

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objItem = objWMIService.Get("SystemRestore")
errResults = objItem.CreateRestorePoint _
    ("Scripted restore", DEVICE_DRIVER_INSTALL, BEGIN_SYSTEM_CHANGE)
Disable Full System Restore
About: Desktop Management

Disables system restore on a computer. This is equivalent to selecting the checkbox Turn off System Restore (found by right-clicking My Computer, clicking Properties, and then clicking on the System Restore tab in the resulting dialog box).

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objItem = objWMIService.Get("SystemRestore")
errResults = objItem.Disable("")
Enable Full System Restore
About: Desktop Management

Enables system restore on a computer. This is equivalent to clearing the checkbox Turn off System Restore (found by right-clicking My Computer, clicking Properties, and then clicking on the System Restore tab in the resulting dialog box).

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objItem = objWMIService.Get("SystemRestore")
errResults = objItem.Enable("")
List All Existing Restore Points
About: Desktop Management

Returns a list of all system restore points stored on a computer, as well as detailed information about each of those restore points.

Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set colItems = objWMIService.ExecQuery("Select * from SystemRestore")
If colItems.Count = 0 Then
    WScript.Echo "No restore point in system."
Else
    For Each objItem in colItems
        Wscript.Echo "Name: " & objItem.Description
        Wscript.Echo "Number: " & objItem.SequenceNumber
        Select Case objItem.RestorePointType
      Case 0 strRestoreType = "Application installation"
            Case 1 strRestoreType = "Application uninstall"
            Case 6 strRestoreType = "Restore"
            Case 7 strRestoreType = "Checkpoint"
            Case 10 strRestoreType = "Device drive installation"
            Case 11 strRestoreType = "First run"
            Case 12 strRestoreType = "Modify settings"
            Case 13 strRestoreType = "Cancelled operation"
            Case 14 strRestoreType = "Backup recovery"
            Case Else strRestoreType = "Unknown"
        End Select
        Wscript.Echo "Restore Point Type: " & strRestoreType
 
        dtmConvertedDate.Value = objItem.CreationTime
        dtmCreationTime = dtmConvertedDate.GetVarDate
        Wscript.Echo "Time: " & dtmCreationTime
     Next
End If
List System Restore Configuration Values
About: Desktop Management

Displays the current system restore configuration settings on a computer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set colItems = objWMIService.ExecQuery("Select * from SystemRestoreConfig")

For Each objItem in colItems
    Wscript.Echo "Disk Percent: " & objItem.DiskPercent
    Wscript.Echo "Global Interval (in seconds): " & objItem.RPGlobalInterval 
    Wscript.Echo "Life Interval (in seconds): " & objItem.RPLifeInterval
    If objItem.RPSessionInterval = 0 Then
        Wscript.Echo "Session Interval: Feature not enabled." 
    Else
        Wscript.Echo "Session Interval (in seconds): " & _
            objItem.RPSessionInterval
    End If
Next
List the Results of the Last System Restore
About: Desktop Management

Returns the results (failed, succeeded, interrupted) of the last system restore performed on a computer.

strComputer = "."
 
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objItem = objWMIService.Get("SystemRestore")
errResults = objItem.GetLastRestoreStatus()
 
Select Case errResults
    Case 0 strRestoreStatus = "The last restore failed."
    Case 1 strRestoreStatus = "The last restore was successful."
    Case 2 strRestoreStatus = "The last restore was interrupted."
End Select
 
Wscript.Echo strRestoreStatus
Modify System Restore Configuration Values
About: Desktop Management

Modifies the system restore configuration values on a computer, setting the global interval to 100,000 seconds; the life interval to 8,000,000 seconds; and the session interval to 500,000 seconds.

Const GLOBAL_INTERVAL_IN_SECONDS = 100000
Const LIFE_INTERVAL_IN_SECONDS = 8000000
Const SESSION_INTERVAL_IN_SECONDS = 500000
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\default")

Set objItem = objWMIService.Get("SystemRestoreConfig='SR'")
objItem.DiskPercent = 10
objItem.RPGlobalInterval = GLOBAL_INTERVAL_IN_SECONDS
objItem.RPLifeInterval = LIFE_INTERVAL_IN_SECONDS
objItem.RPSessionInterval = SESSION_INTERVAL_IN_SECONDS
objItem.Put_
Activate Windows Offline
About: Desktop Management

Uses the offline method to activate Windows. Requires a valid activation number.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colWindowsProducts = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")

For Each objWindowsProduct in colWindowsProducts
    objWindowsProduct.ActivateOffline("1234-1234")
Next
Activate Windows Online
About: Desktop Management

Uses the online method to activate Windows. Requires an active Internet connection.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colWindowsProducts = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")

For Each objWindowsProduct in colWindowsProducts
    objWindowsProduct.ActivateOnline()
Next
List Windows Product Activation Status
About: Desktop Management

Returns product activation information for a computer.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colWPA = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")

For Each objWPA in colWPA
    Wscript.Echo "Activation Required: " & objWPA.ActivationRequired
    Wscript.Echo "Description: " & objWPA.Description
    Wscript.Echo "Product ID: " & objWPA.ProductID
    Wscript.Echo "Remaining Evaluation Period: " & _
        objWPA.RemainingEvaluationPeriod
    Wscript.Echo "Remaining Grace Period: " & objWPA.RemainingGracePeriod
    Wscript.Echo "Server Name: " & objWPA.ServerName
Next
Suppress Windows Activation Notices
About: Desktop Management

Suppresses the Windows Activation reminder notices on a computer. This does not preclude the need to activate the computer; it simply prevents users from seeing the periodic reminders.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colWPASettings = objWMIService.ExecQuery _
    ("Select * from Win32_WindowsProductActivation")
 
For Each objWPASetting in colWPASettings
    objWPASetting.SetNotification(0)
Next
Add “Command Prompt Here” to Windows Explorer
About: Desktop Management

Adds a Command Prompt Here command to the Windows Explorer system menu. If a user selects Command Prompt Here from the system menu, a command window will be displayed, open to the same folder as the current Windows Explorer folder.

Set objShell = CreateObject("WScript.Shell")
 
objShell.RegWrite "HKCR\Folder\Shell\MenuText\Command\", _
    "cmd.exe /k cd " & chr(34) & "%1" & chr(34)
objShell.RegWrite "HKCR\Folder\Shell\MenuText\", "Command Prompt Here"
Add a Template to the Windows Explorer New Menu
About: Desktop Management

Demonstrates how to add VBScript Script File to the New context menu in Windows Explorer. Requires a script template named Template.vbs to be in the \Windows\System32\ShellExt folder (on Windows XP and Windows Server 2003), or in the \Winnt\ShellNew folder (Windows 2000).

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.RegWrite "HKCR\.VBS\ShellNew\FileName","template.vbs"
List Desktop Settings
About: Desktop Management

Lists the current desktop settings on a computer.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_Desktop")

For Each objItem in colItems
    Wscript.Echo "Border Width: " & objItem.BorderWidth
    Wscript.Echo "Caption: " & objItem.Caption
    Wscript.Echo "Cool Switch: " & objItem.CoolSwitch
    Wscript.Echo "Cursor Blink Rate: " & objItem.CursorBlinkRate
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "Drag Full Windows: " & objItem.DragFullWindows
    Wscript.Echo "Grid Granularity: " & objItem.GridGranularity
    Wscript.Echo "Icon Spacing: " & objItem.IconSpacing
    Wscript.Echo "Icon Title Face Name: " & objItem.IconTitleFaceName
    Wscript.Echo "Icon Title Size: " & objItem.IconTitleSize
    Wscript.Echo "Icon Title Wrap: " & objItem.IconTitleWrap
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Pattern: " & objItem.Pattern
    Wscript.Echo "Screen Saver Active: " & objItem.ScreenSaverActive
    Wscript.Echo "Screen Saver Executable: " & _
        objItem.ScreenSaverExecutable
    Wscript.Echo "Screen Saver Secure: " & objItem.ScreenSaverSecure
    Wscript.Echo "Screen Saver Timeout: " & objItem.ScreenSaverTimeout
    Wscript.Echo "Setting ID: " & objItem.SettingID
    Wscript.Echo "Wallpaper: " & objItem.Wallpaper
    Wscript.Echo "Wallpaper Stretched: " & objItem.WallpaperStretched
    Wscript.Echo "Wallpaper Tiled: " & objItem.WallpaperTiled
Next