Friday, 28 March 2014

The server cannot handle directory requests ldap error

Description:

I got the LdapConnection exception The server cannot handle directory requests with the following Stack Trace when I try to restore a deleted AD user in C#.

Message: The server cannot handle directory requests

Stack Trace: at System.DirectoryServices.Protocols.LdapConnection.ConstructResponse(Int32 messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, Boolean exceptionOnTimeOut) at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request, TimeSpan requestTimeout) at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request)

Here is my C# code:

private static void RestoreTombstone(string dcName, string deletedObjectDN, string deletedUserCN,string lastKnownParent, NetworkCredential credential)
    {
        LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(dcName), credential, AuthType.Negotiate);
        connection.Bind();
        connection.SessionOptions.ProtocolVersion = 3;

        // to remove value of isDeleted attribute
        DirectoryAttributeModification deleteIsDeletedAttr = new DirectoryAttributeModification();
        deleteIsDeletedAttr.Name = "isDeleted";
        deleteIsDeletedAttr.Operation = DirectoryAttributeOperation.Delete;

        string newDN = string.Format("cn={0},{1}", deletedUserCN, lastKnownParent); 
        // to remove value of isDeleted attribute
        DirectoryAttributeModification replaceDNAttr = new DirectoryAttributeModification();
        replaceDNAttr.Name = "distinguishedName";
        replaceDNAttr.Operation = DirectoryAttributeOperation.Replace;
        replaceDNAttr.Add(newDN);

        ModifyRequest request = new ModifyRequest(deletedObjectDN, new DirectoryAttributeModification[] { deleteIsDeletedAttr, replaceDNAttr });
        request.Controls.Add(new ShowDeletedControl());

        try
        {
            ModifyResponse response = (ModifyResponse)connection.SendRequest(request);
            if (response.ResultCode == ResultCode.Success)
            {}
        }
        catch (Exception exception)
        {Console.WriteLine("Failed to Restore Deleted AD User:" + exception.Message);}
    }


Fix or Solution to the LDAP error: The server cannot handle directory requests

After I have googled and analyzed some time, I found the root cause for the issue is invalid or unaccepted value in DirectoryAttributeModification. Yes while we use DirectoryAttributeModification control to change the attribute value, we should give valid value for the corresponding attribute to modify.

In our case, we are changing deleted user's distinguishedName attribute into new value in C#. to make new DN, we are joining user's CN and lastKnowParent.

CN: Test,User
lastKnowParent: OU=TestOU,DC=MyDomain,DC=Com

We have no problem with lastKnowParent, but in CN we have the special character , (comma), this special character is not allowed in distinguishedName. so this special character is the root cause for the error The server cannot handle directory requests in our code. so we need to include escape sequence for that special character.

Now I have changed my code like
deletedUserCN=deletedUserCN.Replace(@",", @"\,")
 string newDN = string.Format("cn={0},{1}", deletedUserCN, lastKnownParent);
This fix solved the error 'The server cannot handle directory requests' for us. If you face this error in any other situation with LdapConnection just check whether you are supplying valid input values.

Thanks,
Morgan
Software Developer

Restore Deleted AD User in C#

Description:

In this article, I am going write C# code to Restore Deleted Active Directory User Account. This Restore process contains following three operations.

Main function to Restore Deleted User in C#

Before proceed, you need to add two dll references System.DirectoryServices and System.DirectoryServices.Protocols.
    static void Main()
    {
        string domainDN = "DC=Work2008,DC=local";
        string domainController = "DevDC";
        string delUser_samAccountName = "del_test";
        SearchResult searchResult = SearchAndGetDeletedObject(domainDN, delUser_samAccountName);

        if (searchResult != null)
        {
            string deletedObjectDN = searchResult.Properties["distinguishedName"][0].ToString();
            string newDN = GetNewDNToRestore(searchResult);
            NetworkCredential netCredential = new NetworkCredential("Administrator", "Password1234", "work2008.local");
            RestoreTombstone(deletedObjectDN, newDN, domainController, netCredential);
        }
    }

Search And Find Deleted AD User by samAccountName in C#

Here, we are searching Deleted AD user by its samAccountName, you can also search it by ObjectGuid or ObjectSID.
private static SearchResult SearchAndGetDeletedObject(string domainDN, string deletedUserName)
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://CN=Deleted Objects," + domainDN, "Administrator", "Password1234");
        dirEntry.AuthenticationType = AuthenticationTypes.FastBind | AuthenticationTypes.Secure;

        DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry, string.Format("(&(isDeleted=TRUE)(sAMAccountName={0}))",
                    deletedUserName));

        dirSearcher.CacheResults = false;
        dirSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
        dirSearcher.Tombstone = true;

        SearchResult searchResult = dirSearcher.FindOne();
        return searchResult;
    }

Make new DistinguishedName to Restore Deleted AD User from CN and LastKnownParent

Here, we are making new DistinguishedName to Restore Deleted AD User. We need to move this user to the OU where it was located before delete. We can get Old OU's DN from the attribute lastKnownParent.
private static string GetNewDNToRestore(SearchResult searchResult)
    {
        string newDN = string.Empty;

        string cn = searchResult.Properties["cn"][0].ToString().Split(new char[] { '\n' })[0];

        // Remove special characters 
        cn = cn.Replace(@"\", @"\\");
        cn = cn.Replace(@",", @"\,");

        string lastKnownParent = searchResult.Properties["lastKnownParent"][0].ToString();

        newDN = string.Format("cn={0},{1}", cn, lastKnownParent);

        return newDN;
    }

Restore Deleted Active Directory User from Tombstone in C#

This is the final process to Move Deleted AD user into Old OU where it was located before delete.
private static void RestoreTombstone(string deletedObjectDN, string newDN, string domainControllerName, NetworkCredential credential)
    {
        LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(domainControllerName), credential, AuthType.Negotiate);
        using (connection)
        {
            connection.Bind();
            connection.SessionOptions.ProtocolVersion = 3;

            // to remove value of isDeleted attribute
            DirectoryAttributeModification deleteIsDeletedAttr = new DirectoryAttributeModification();
            deleteIsDeletedAttr.Name = "isDeleted";
            deleteIsDeletedAttr.Operation = DirectoryAttributeOperation.Delete;

            // to remove value of isDeleted attribute
            DirectoryAttributeModification replaceDNAttr = new DirectoryAttributeModification();
            replaceDNAttr.Name = "distinguishedName";
            replaceDNAttr.Operation = DirectoryAttributeOperation.Replace;
            replaceDNAttr.Add(newDN);

            ModifyRequest request = new ModifyRequest(deletedObjectDN, new DirectoryAttributeModification[] { deleteIsDeletedAttr, replaceDNAttr });
            request.Controls.Add(new ShowDeletedControl());

            try
            {
                ModifyResponse response = (ModifyResponse)connection.SendRequest(request);
                if (response.ResultCode == ResultCode.Success)
                {
                    Console.WriteLine("Deleted Active Directory User Restored Successfully.");
                }
                else
                {
                    Console.WriteLine("Failed to Restore Deleted AD User.");
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Failed to Restore Deleted AD User:" + exception.Message);
            }
        }
    }

Thanks,
Morgan
Software Developer

Thursday, 27 March 2014

Event ID 4625 An account failed to log on

Description:

    In this article, I am going to explain about the Local Computer Logon Failure Event 4625. This event will get logged whenever an user tries to login with bad or wrong credentials. Here we will discus about how to Enable Event 4625 through local security policy and Auditpol command in local computer and how to enable Event 4625 in Active Directory based domain environment via Group Policy Object. Here, we will also discus about how to Stop or Disable the event 4625 when you don't want logon failure activity.

This is event controlled by Logon/Logoff (Audit logon events) category in Audit policy settings. Other important events controlled by this audit policy setting are 4624, 4648, 4634 and 4672

Refer this article Tracking User Logon Activity using Logon and Logoff Events to know about how to track user's logon duration from logon 4624 and logoff 4634 events.

Summary:


Event ID 4625 Sample Source:

Description: An account failed to log on.

Subject:
       Security ID: SYSTEM
       Account Name: MyPC$
       Account Domain: TestDomain
       Logon ID: 0x0
Logon Type: 
Account For Which Logon Failed:
       Security ID: S-1-5-21-822115511-2935354860-794628881-514
       Account Name: Ltest
       Account Domain: TestDomain
Failure Information:
       Failure Reason: Unknown user name or bad password.
       Status: 0xc000006d
       Sub Status: 0xc0000064
Process Information:
       Caller Process ID:       0x0
       Caller Process Name:       -
Network Information:
       Workstation Name: MyPC
       Source Network Address: 192.178.87.231
       Source Port: 
Detailed Authentication Information:
       Logon Process:              NtLmSsp
       Authentication Package:       NTLM
       Transited Services:       -
       Package Name (NTLM only):       -
       Key Length:              0

This event is generated when a logon request fails. It is generated on the computer where access was attempted.
The Subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service or a local process such as Winlogon.exe or Services.exe.
The Logon Type field indicates the kind of logon that was requested. The most common types are 2 (interactive) and 3 (network).
The Process Information fields indicate which account and process on the system requested the logon.
The Network Information fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.
The authentication information fields provide detailed information about this specific logon request.
       - Transited services indicate which intermediate services have participated in this logon request.
       - Package name indicates which sub-protocol was used among the NTLM protocols.
       - Key length indicates the length of the generated session key. This will be 0 if no session key was requested.

Enable event 4625 via Local Security Policy

Steps to enable event 4625 through Local Security Policy:

1. Run the command secpol.msc to open Local Security Policy.

Event 4625 - Enable and Stop Logon Failure Event 4625

2. In Local Security Policy console, go to the node Audit Policy (Security Settings -> Local Policies-> Audit Policy).

Event 4625 - Enable and Stop Logon Failure Event

3. In right side pane, double-click the policy Audit logon events.

4. Now check the Failure audit and click Apply to configure logon failure event 4625.

Event 4625 - Enable and Stop Event 4625


Now, you have successfully configured audit setting to log event 4625 in local computer. if you working in Active Directory based domain environment and if you want to configure this settings in all the computers that exists in domain, you need to achieve this by applying audit setting through any of Group Policy Object.

How to enable event 4625 through Group Policy

Steps to enable event 4625 through GPO:

1. Open Group Policy Management Console by running the command gpmc.msc

2. Expand the domain node,  then right-click on the Default Domain Policy, and click Edit option

Enable Event 4625 logon failure via GPO

3. Expand the Computer Configuration node, go to the node Audit Policy (Computer Configuration->Policies->Windows Settings->Security Settings->Local Policies->Audit Policy).

4. Navigate to the right side pane, select the policy Audit logon events, and set the Failure audit value.

Enable Event 4625 via GPO

5. In Windows 7/Server 2008 R2 and later versions, you can also enable Event ID 4625 through Advanced Audit Policy Configuration.  Expand Computer Configuration, and go to the node Advanced Audit Policy Configuration (Computer Configuration->Polices->Windows Settings->Security Settings->Advanced Audit Policy Configuration)

6. Expand this node, go to Logon/Logoff (Audit Polices-> Logon/Logoff ), then select the Setting

Audit Logon, and set its value as Failure

Enable Event 4625 via GPO

8. Run the command GPUpdate /force to apply this setting in all the Computers

Enable Event 4625 via GPO


How to enable event 4625 using Auditpol

     Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions. By using Auditpol, we can get/set Audit Security settings per user level and computer level.

   Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable audit Event 4625 by using the following command
Auditpol /set /subcategory:"Logon" /failure:enable

How to stop/disable Event 4625

You can disable or stop the logon failure audit Event ID 4625 by using the following command
Auditpol /set /subcategory:"Logon" /failure:disable

You can also stop this event by removing the Failure audit setting from the GPO in the setting path  Computer Configuration->Polices->Windows Settings->Security Settings->Advanced Audit Policy Configuration->Audit Polices->Logon/Logoff->Audit Logon.


 Note: You need to refresh/update GPO for every change by running the command GPUpdate/force.


Note : This article is applies to Windows Server 2008,Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8.

Thanks,
Morgan
Software Developer

Wednesday, 26 March 2014

VBScript to Disable AD User Account by UserName

In this article, I am going to write vbscript code to Disable Active Directory user account and vbscript to disable ad user by asking UserName dynamically from user.

Note: You should run this VBScript code on a machine with windows Active Directory domain.

Summary:

VBScript to Disable Active Directory User by UserName

1. Copy the below example vbscript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName with your own user's name or samAccountName to disable.
3. Save the file with a .vbs extension, for example: DisableADUserByUserName.vbs
4. Double-click the vbscript file (or Run this file from command window) to disable AD user.

Click to get vbscript code as a file Download DisableADUserByUserName.vbs

' DisableADUserByUserName.vbs
' Sample VBScript to disable AD user .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset,strUserDN
Dim strUserName,objUser

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

strUserName="LTest"

' Filter on user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(|(name="& strUserName &")(samaccountname="& strUserName &")))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
IF(adoRecordset.EOF<>True) Then
    ' Retrieve values and display.
    strUserDN = adoRecordset.Fields("distinguishedname").value
    Set objUser = GetObject("LDAP://"& strUserDN) 
        objUser.AccountDisabled = True
        objUser.SetInfo

       WScript.Echo "The user '"& strUserName &"' disabled successfully..."

Else 
      WScript.Echo "No user found with the name '"& strUserName &"'"
 End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

VBScript to Disable Active Directory User by UserName as Dynamic input

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example: DisableADUserByDynamicUserName.vbs
3. Double-click the vb script file (or Run this file from command window) to disable AD user.
4. Enter the name or samAccountName of the user in the input text box and click OK to proceed.

VBScript to Disable Active Directory User Account

Click to get vbscript code as a file Download DisableADUserByDynamicUserName.vbs

' DisableADUserByDynamicUserName.vbs
' Sample VBScript to disable AD user by Dynamic UserName .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset,strUserDN
Dim strUserName,objUser

' Asks user name from user.
Do
   strUserName = InputBox ("Please enter an UserName to disable")
   If strUserName = "" then
      Msgbox "No user name entered"
   end if
Loop Until strUserName <> ""

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' Filter on user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(|(name="& strUserName &")(samaccountname="& strUserName &")))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
IF(adoRecordset.EOF<>True) Then
    ' Retrieve values and display.
    strUserDN = adoRecordset.Fields("distinguishedname").value
    Set objUser = GetObject("LDAP://"& strUserDN) 
        objUser.AccountDisabled = True
        objUser.SetInfo

       WScript.Echo "The user '"& strUserName &"' disabled successfully..."

Else 
      WScript.Echo "No user found with the name '"& strUserName &"'"
 End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

Tuesday, 25 March 2014

Event ID 4767: A user account was unlocked

Description:

  In this article, I am going to explain about the Active Directory user account unlock Event 4767. It also includes the steps to enable Event 4767 and disable 4767 user account unlock event. This event comes under the Account Management category/User Account Management subcategory of Security Audit.

Note: Equivalent event of 4767 in server 2003/xp based machine is 671.

Summary:

  1. Event 4767 Example source
  2. Steps to enable 4767 Event through Default Domain Controllers Group Policy
  3. How to User Account Unlock Event 4767 via Auditpol
  4. Steps to disable/stop Event ID 4767

Event 4767 Example source

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          3/25/2014 5:11:42 PM
Event ID:      4767
Task Category: User Account Management
Level:         Information
Keywords:      Audit Success
User:          N/A
Computer:      devDC.Work2008.local
Description:
A user account was unlocked.

Subject:
 Security ID:  WORK2008\Administrator
 Account Name:  Administrator
 Account Domain:  WORK2008
 Logon ID:  0x2c3aaf

Target Account:
 Security ID:  WORK2008\LTest
 Account Name:  LTest
 Account Domain:  WORK2008


Steps to enable 4767 Event ID through Default Domain Controllers Group Policy

1. Open Group Policy Management Console by running the command gpmc.msc

2. Expand the domain node, expand the Domain Controllers OU, then Right-click on the Default Domain Controllers Policy, and click the Edit option

Steps to Enable Event ID 4767: A user account was unlocked


3. Expand the Computer Configuration node, go to the node Audit Policy(Computer Configuration->Policies->Windows Settings->Security Settings->Local Policies->Audit Policy).

4. Navigate to the right side pane, select the policy Audit account management, and set the success audit value.

Steps to enable Event ID 4740 - Active Directory user account unlocked Event


4. In Windows 2008 R2 and later versions, you can also control Event ID 4767 through Advanced Audit Policy configuration. Expand the Computer Configuration node, go to the node Advanced Audit Policy Configuration(Computer Configuration->Policies->Windows Settings->Security Settings->Advanced Audit Policy Configuration->Audit Policies). And click Account Maangement, in the right side pane, enable success auditing for Audit User Account Management subcategory.

Steps to Enable User Account unlock Event ID 4767


5. To update or refresh GPO settings, run the command gpupdate/force
Steps to Enable User Account unlock Event 4767



How to enable User Account Unlock Event 4767 via Auditpol

Auditpol.exe is the command line utility tool to change Audit Security settings as category and sub-category level. It is available by default Windows 2008 R2 and later versions/Windows 7 and later versions.

By using Auditpol, we can get/set Audit Security settings per user level and computer level.

Note: You should run Auditpol command with elevated privilege (Run As Administrator);

You can enable Active Directory User Account Unlock audit event (Event ID 4740) through User Account Management subcategory by using the following command
auditpol /set /subcategory:"User Account Management" /success:enable
To update or refresh GPO settings, run the command gpupdate/force


Steps to disable/stop User Account Unlock Event 4767

You can disable or stop Active Directory User Account Unlock audit event (Event ID 4767) by removing success audit in User Account Management subcategory by using the following command.
auditpol /set /subcategory:"User Account Management" /success:disable
You can also stop this event by removing the success setting from the Default Domain Controllers GPO in the setting path Computer Configuration->Polices->Windows Settings->Security Settings->Audit Policy->Account Management


Note : This article is applies to Windows Server 2008,Windows Server 2008 R2, Windows Server 2012, Windows 7 and Windows 8.

Thanks,
Morgan
Software Developer

Monday, 24 March 2014

Read CSV File and Insert Into SQL Server using Bulk Insert

Description:

Hi, in this article, I am going to write sql script to Import or Insert CSV file data into SQL Server using Bulk Insert and C# code to Read CSV file and Insert into SQL Server using Bulk Insert.

SQL Script to Import CSV file into SQL Server using Bulk Insert

Here, we have considered StudentsData table with three columns to read and store data from CSV file.
Use MorganDB
GO
Create Table StudentsData
(
UserName VARCHAR(250),
City VARCHAR(250),
MailID VARCHAR(250),
);
The data we are going to load into SQL Server using Bulk Insert is stored in the CSV File - UserData.CSV . The below image shows sample CSV content.

Import CSV File Into SQL Server using Bulk Insert

Now, to read CSV file, you can use following SQL Script with Bulk Insert command
Use MorganDB
GO
BULK INSERT StudentsData
FROM 'C:\Users\Administrator\Desktop\UserData.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR =',',
ROWTERMINATOR ='\n'
)

Here, we have set FIRSTROW = 2 to exclude first row and start read data from second row in CSV file. this is because as you know we have treated first row as column header in CSV file and FIELDTERMINATOR is used to separate column values by char ',' and ROWTERMINATOR is used to split rows by the char '\n'.

Imported CSV File Output in SQL Server
Use [MorganDB]
Go
SELECT [UserName],[City],[MailID]
 FROM [StudentsData]

Read or Import CSV File Into SQL Server using Bulk Insert in C#


Read or Import CSV file into SQL Server using Bulk Insert in C#

You can use the following C# function to Read or Import CSV file data into SQL Server.
  static void Main(string[] args)
    {
        ImportCSVFileIntoSQLServer();
    }

  private static void ImportCSVFileIntoSQLServer()
    {
        try
        {
            using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.\SQLExpress; 
                     Initial Catalog=MorganDB; Integrated Security=SSPI;"))
            {
                sqlconnection.Open();

                SqlCommand command = new SqlCommand(@"BULK INSERT StudentsData
                                        FROM 'C:\Users\Administrator\Desktop\UserData.csv'
                                        WITH
                                        (
                                        FIRSTROW = 2,
                                        FIELDTERMINATOR =',',
                                        ROWTERMINATOR ='\n'
                                        )", sqlconnection);

                command.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }


Thanks,
Morgan
Software Developer

Friday, 21 March 2014

Set Logon as batch job rights to User by Powershell, C# and CMD

Description:

In this article, I am going to explain about how to set or grant Logon as batch job
rights/permission/privilege using Local Security Policy, Powershell, C# and Command Line tool.

Summary:


Set Logon as batch job rights to user using Local Security Policy GUI

Follow the below steps to set Logon as batch job rights via Local Security Policy

1. Open the Run window by pressing 'Windows' + 'R'  keys.
2. Type the command secpol.msc in the text box and click OK.
Set Log on as batch job right to user by C#, Powershell, Command Prompt
3. Now the Local Security Policy window will be open, in that window navigate to the node User Rights Assignment (Security Settings -> Local Polices ->User Rights Assignment). In right side pane, search and select the policy Log on as batch job.


Set Logon as a batch job rights to User by Powershell, C#, Command Prompt


4. Double-click on the policy Log on as batch job, in the opened window click the button Add User or Group, select the user account you want to set logon as a batch job rights and click OK, and click Apply button to finish.
Set Logon as batch job rights to User by Powershell, C# and CMD


Note: If you see Log on as batch job policy with locked symbol, you can't edit Logon as a batch job rights through this Local Security policy, because in that case this policy setting is enforced or inherited from some other Group Policy Object like Default Domain Policy or Default Domain Controller Policy. so you need to edit this policy setting via the inherited GPO.
Set Logon as a batch job rights/permission/privilege to User by CMD, C#, Powershell, Command Prompt



Set or Grant User Logon as batch job rights via Powershell

 We can set the Logon as a batch job right to user in Powershell by importing the third party DLL ( Carbon ). Before you run the below script you need to the download latest Carbon files from here Download Carbon DLL.

Steps to follow to set Logon as batch job rights via Powershell :

  1. Download latest Carbon files from here Download Carbon DLL.
  2. If you have downloaded the files, extract the zip file and you could see the Carbon DLL inside bin folder (In my case: C:\Users\Administrator\Downloads\Carbon\bin\Carbon.dll).
  3. Copy the below Powershell script commands and place it notepad or textfile.
  4. Now you can replace your Carbon DLL path in following script for the variable $CarbonDllPath
  5. You can also replace the user identity that you are going to set log on as batch job rights in the variable $Identity
  6. Now run as Powershell window with Admin Privilege (Run as Administrator)
  7. Copy the edited Powershell script and Run it in Powershell to set log on as batch job rights.

$Identity = "DomainName\Svc_User_account"
$privilege = "SeBatchLogonRight"

$CarbonDllPath = "C:\Users\Administrator\Downloads\Carbon\bin\Carbon.dll"

[Reflection.Assembly]::LoadFile($CarbonDllPath)

[Carbon.Lsa]::GrantPrivileges( $Identity , $privilege )

Powershell output:
Set Logon as batch job rights to User by Powershell, C# and CMD


Other web site links for Carbon DLL:
 https://bitbucket.org/splatteredbits/carbon/downloads
 http://pshdo.com/
 http://get-carbon.org/help/Grant-Privilege.html

Set or Grant User Logon as a batch job right/permission to user using C#

You can use the function GrantUserLogonAsBatchJob to set logon as a batch job right to user using C# code. This function uses the class LsaWrapper.

static void GrantUserLogonAsBatchJob(string userName)
{
    try
    {
        LsaWrapper lsaUtility = new LsaWrapper();

        lsaUtility.SetRight(userName, "SeBatchLogonRight");

        Console.WriteLine("Logon as batch job right is granted successfully to " + userName);
    }            
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
LsaWrapper class file
public class LsaWrapper
{
// Import the LSA functions

[DllImport("advapi32.dll", PreserveSig = true)]
private static extern UInt32 LsaOpenPolicy(
    ref LSA_UNICODE_STRING SystemName,
    ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
    Int32 DesiredAccess,
    out IntPtr PolicyHandle
    );

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern long LsaAddAccountRights(
    IntPtr PolicyHandle,
    IntPtr AccountSid,
    LSA_UNICODE_STRING[] UserRights,
    long CountOfRights);

[DllImport("advapi32")]
public static extern void FreeSid(IntPtr pSid);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, PreserveSig = true)]
private static extern bool LookupAccountName(
    string lpSystemName, string lpAccountName,
    IntPtr psid,
    ref int cbsid,
    StringBuilder domainName, ref int cbdomainLength, ref int use);

[DllImport("advapi32.dll")]
private static extern bool IsValidSid(IntPtr pSid);

[DllImport("advapi32.dll")]
private static extern long LsaClose(IntPtr ObjectHandle);

[DllImport("kernel32.dll")]
private static extern int GetLastError();

[DllImport("advapi32.dll")]
private static extern long LsaNtStatusToWinError(long status);

// define the structures

private enum LSA_AccessPolicy : long
{
    POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
    POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
    POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
    POLICY_TRUST_ADMIN = 0x00000008L,
    POLICY_CREATE_ACCOUNT = 0x00000010L,
    POLICY_CREATE_SECRET = 0x00000020L,
    POLICY_CREATE_PRIVILEGE = 0x00000040L,
    POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
    POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
    POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
    POLICY_SERVER_ADMIN = 0x00000400L,
    POLICY_LOOKUP_NAMES = 0x00000800L,
    POLICY_NOTIFICATION = 0x00001000L
}

[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
    public int Length;
    public IntPtr RootDirectory;
    public readonly LSA_UNICODE_STRING ObjectName;
    public UInt32 Attributes;
    public IntPtr SecurityDescriptor;
    public IntPtr SecurityQualityOfService;
}

[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
    public UInt16 Length;
    public UInt16 MaximumLength;
    public IntPtr Buffer;
}
/// 
//Adds a privilege to an account

/// Name of an account - "domain\account" or only "account"
/// Name ofthe privilege
/// The windows error code returned by LsaAddAccountRights
public long SetRight(String accountName, String privilegeName)
{
    long winErrorCode = 0; //contains the last error

    //pointer an size for the SID
    IntPtr sid = IntPtr.Zero;
    int sidSize = 0;
    //StringBuilder and size for the domain name
    var domainName = new StringBuilder();
    int nameSize = 0;
    //account-type variable for lookup
    int accountType = 0;

    //get required buffer size
    LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

    //allocate buffers
    domainName = new StringBuilder(nameSize);
    sid = Marshal.AllocHGlobal(sidSize);

    //lookup the SID for the account
    bool result = LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize,
                                    ref accountType);

    //say what you're doing
    Console.WriteLine("LookupAccountName result = " + result);
    Console.WriteLine("IsValidSid: " + IsValidSid(sid));
    Console.WriteLine("LookupAccountName domainName: " + domainName);

    if (!result)
    {
        winErrorCode = GetLastError();
        Console.WriteLine("LookupAccountName failed: " + winErrorCode);
    }
    else
    {
        //initialize an empty unicode-string
        var systemName = new LSA_UNICODE_STRING();
        //combine all policies
        var access = (int) (
                                LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                                LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                                LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                                LSA_AccessPolicy.POLICY_CREATE_SECRET |
                                LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                                LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                                LSA_AccessPolicy.POLICY_NOTIFICATION |
                                LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                                LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                                LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                                LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                                LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                                LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                            );
        //initialize a pointer for the policy handle
        IntPtr policyHandle = IntPtr.Zero;

        //these attributes are not used, but LsaOpenPolicy wants them to exists
        var ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
        ObjectAttributes.Length = 0;
        ObjectAttributes.RootDirectory = IntPtr.Zero;
        ObjectAttributes.Attributes = 0;
        ObjectAttributes.SecurityDescriptor = IntPtr.Zero;
        ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;

        //get a policy handle
        uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, access, out policyHandle);
        winErrorCode = LsaNtStatusToWinError(resultPolicy);

        if (winErrorCode != 0)
        {
            Console.WriteLine("OpenPolicy failed: " + winErrorCode);
        }
        else
        {
            //Now that we have the SID an the policy,
            //we can add rights to the account.

            //initialize an unicode-string for the privilege name
            var userRights = new LSA_UNICODE_STRING[1];
            userRights[0] = new LSA_UNICODE_STRING();
            userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName);
            userRights[0].Length = (UInt16) (privilegeName.Length*UnicodeEncoding.CharSize);
            userRights[0].MaximumLength = (UInt16) ((privilegeName.Length + 1)*UnicodeEncoding.CharSize);

            //add the right to the account
            long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
            winErrorCode = LsaNtStatusToWinError(res);
            if (winErrorCode != 0)
            {
                Console.WriteLine("LsaAddAccountRights failed: " + winErrorCode);
            }

            LsaClose(policyHandle);
        }
        FreeSid(sid);
    }

    return winErrorCode;
}    
}


Grant Logon as a batch job right to user via Command Line

You can use the NTRights.exe utility to grant or deny user rights to users and groups from a command line or a batch file. The NTRights.exe utility is included in the Windows NT Server 4.0 Resource Kit Supplement 3. Refer: http://support.microsoft.com/kb/266280

Set Logon As Batch Job right
ntrights +r SeBatchLogonRight -u "Domain\Svc_Test_user"
Revoke Logon As Batch Job right
ntrights -r SeBatchLogonRight -u "Domain\Svc_Test_user"

Thanks,
Morgan
Software Developer
---------------------

Monday, 17 March 2014

VBScript to Unlock AD User Account

Description:

In this article, I am going write vbscript code to Unlcok active directory user account by asking account name from user and vbscript code to Unlock all the currently Locked Out AD users in Entire Domain and Specific OU.

Summary:


VBScript to Unlock AD User Account

1. Copy the below example vbscript code and paste it in notepad or in vbscript editor.
2. Save the file with a .vbs extension, for example: UnlockADUser.vbs
3. Double-click the vbscript file (or Run this file from command window) to unlock active directory user.
4. Enter the user name to Unlock and click OK to proceed.

Unlock Currently Locked out Active Directory Users using VBScript

 Click to get vbscript source code as file Download UnlockADUser.vbs
' UnlockADUser.vbs
' Sample VBScript to Unlock Active Directory user .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim strUserName,objUser

' Asks username from user to Unlock.
Do
   strUserName= InputBox ("Please enter user name")
   If strUserName= "" then
     Wscript.Echo "No user name entered"
   end if
Loop Until strUserName <> ""

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' Filter on user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(|(samaccountname="& strUserName &")(name="& strUserName &")))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

IF(adoRecordset.EOF<>True) Then
      Set objUser = GetObject("LDAP://"& adoRecordset.Fields("distinguishedname").value) 
   If objUser.IsAccountLocked = 0 Then
      Wscript.Echo "The User '" & strUserName & "' was already Unlocked."
   Else
    objUser.IsAccountLocked = 0
    objUser.SetInfo
     WScript.Echo "The user '"& strUserName &"' has been Unlocked successfully."
   End if

Else 
      WScript.Echo "No user found with the name '"& strUserName &"'"
 End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

VBScript to Unlock all the Locked Out User Accounts in Active Directory

1. Copy the below example vbscript code and paste it in notepad or in vbscript editor.
2. Save the file with a .vbs extension, for example: UnLockAllADUsers.vbs
3. Double-click the VBScript file (or Run this file from command window) to Unlock all the Locked Out AD users.

Note: Just uncomment the below line in vbscript file if you want to see the user name who are getting unlocked
' WScript.Echo "The user '"& adoRecordset.Fields("samaccountname").value &"' Unlocked."
and Run script from Command prompt: C:\> CScript C:\Scripts\UnLockAllADUsers.vbs


VBScript Unlock Currently Locked out AD User Accounts in VBScript

 Click to get vbscript source code as a file Download UnLockAllADUsers.vbs
' UnLockAllADUsers.vbs
' Sample VBScript to Find and Unlock all the Currently Locked Out AD users.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes,objUser
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim count_unlockedUsers

count_unlockedUsers = 0

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of getting from "defaultNamingContext"
' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

' Filter to list locked out user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(SAMAccountType=805306368)(LockoutTime>=1))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

  Set objUser = GetObject("LDAP://"& adoRecordset.Fields("distinguishedname").value) 

  If objUser.IsAccountLocked <> 0 Then
     objUser.IsAccountLocked = 0
     objUser.SetInfo
   count_unlockedUsers =count_unlockedUsers +1
 ' Just uncomment the below line if you want to see the user name who are getting unlocked
 ' and Run script from Command prompt: C:\> CScript C:\Scripts\UnLockAllADUsers.vbs
    ' WScript.Echo "The user '"& adoRecordset.Fields("samaccountname").value &"' Unlocked."
   End if

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

IF count_unlockedUsers = 0 Then
    WScript.Echo "No Locked Out AD User Accounts found."
Else
   WScript.Echo "Active Directory User Account(s) Unlocked successfully"& vbCrLf  _ 
   & "No Of Users: "&count_unlockedUsers
End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

VBScript to Unlock AD User Account From Specific 

1. Copy the below example vbscript code and paste it in notepad or a vbscript editor.
2. Change the value for 'varBaseDN' into your own OU's DN .
3. Save the file with a .vbs extension, for example: UnLockADUsersFromOU.vbs
4. Double-click the vbscript file (or Run this file from command window) to unlock locked out AD users From Specific OU.

 Click to get vbscript source code as a file Download UnLockADUsersFromOU.vbs
' UnLockADUsersFromOU.vbs
' Sample VBScript to Find and Unlock all the Locked Out AD users From specific OU.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes,objUser
Dim objRootDSE,strQuery, adoRecordset
Dim count_unlockedUsers

count_unlockedUsers = 0

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

' varBaseDN is the OU DN for AD Serach Scope, you can give your own OU's Distinguished Name here.

varBaseDN = "<LDAP://OU=FTP,DC=work2008,DC=Local>"

' Filter to list locked out user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(SAMAccountType=805306368)(LockoutTime>=1))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

  Set objUser = GetObject("LDAP://"& adoRecordset.Fields("distinguishedname").value) 

  If objUser.IsAccountLocked <> 0 Then
     objUser.IsAccountLocked = 0
     objUser.SetInfo
   count_unlockedUsers =count_unlockedUsers +1
 ' Just uncomment the below line if you want to see the user name who are getting unlocked
 ' and Run script from Command prompt: C:\> CScript C:\Scripts\UnLockADUsersFromOU.vbs
    ' WScript.Echo "The user '"& adoRecordset.Fields("samaccountname").value &"' Unlocked."
   End if

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

IF count_unlockedUsers = 0 Then
    WScript.Echo "No Locked Out AD User Accounts found."
Else
   WScript.Echo "Active Directory User Account(s) Unlocked successfully"& vbCrLf  _ 
   & "No Of Users: "&count_unlockedUsers
End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

Sunday, 16 March 2014

Find and Export Locked-Out AD Users with VBScript

In this article I am going write vbscript code to Find and List Active Directory Locked-Out User Accounts and Export currently Locked-Out User Accounts to CSV file. Here, we are using two attributes LockoutTime and msDS-User-Account-Control-Computed to find currently locked-out users.

Summary:


VBScript to Find and List currently Locked-Out AD Users

1. Copy the below example vbscript code and paste it in notepad or in vbscript editor.
2. Save the file with a .vbs extension, for example: FindLockedoutADUsers.vbs
4. Double-click the vbscript file (or Run this file from command window) to find and list Locked-Out Active Directory users.

Usage in CMD: In Command prompt, you can use built-in utility CScript to run vbscript file
C:\> CScript C:\Scripts\FindLockedoutADUsers.vbs 
-or- 
C:\>CScript C:\Scripts\FindLockedoutADUsers.vbs > C:\Scripts\LockoutUsers.txt 
VBScript to Find and List Locked Out AD Users

 Click to get vbscript source code as a file Download FindLockedoutADUsers.vbs

' FindLockedoutADUsers.vbs
' Sample VBScript to Find and List Locked-Out Active Directory users.
' Author: http://www.morgantechspace.com/
' Usage in CMD: C:\> CScript C:\Scripts\FindLockedoutADUsers.vbs
' -or- C:\>CScript C:\Scripts\FindLockedoutADUsers.vbs > C:\Scripts\LockoutUsers.txt
' ------------------------------------------------------' 
Option Explicit
' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim lockoutFlag
Const Flag_LOCKOUT = 16
' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of getting from "defaultNamingContext"
' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

' Filter to list locked-out user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(SAMAccountType=805306368)(LockoutTime>=1))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "samaccountname,distinguishedname"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ",msDS-User-Account-Control-Computed;subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Ensure the user is still in locked-out state by checking UF_LOCKOUT flag
   ' in the msDS-User-Account-Control-Computed attribute
      
     lockoutFlag = adoRecordset.Fields("msDS-User-Account-Control-Computed").Value

    If (lockoutFlag and Flag_LOCKOUT) Then

      WScript.Echo adoRecordset.Fields("samaccountname").Value &" ---> " _
      & adoRecordset.Fields("distinguishedname").Value

    End If

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Active Directory Locked-out Users listed successfully...

Export Locked-Out AD Users to CSV file using VBScript

1. Copy the below example vbscript code and paste it in notepad or in vbscript editor.
2. Here, I have given csv file path as "ADLockedUsers.csv", this will create ADLockedUsers.csv file where you placed and execute this VB Script file. You can give your own file path like "C:\Users\Administrator\Desktop\ADLockedUsers.csv"
3. Save the file with a .vbs extension, for example: ExportLockedoutADUsers.vbs
4. Double-click the VBScript file (or Run this file from command window) to export Locked-Out Active Directory users into csv file.

 Click to get vbscript source code as a file Download ExportLockedoutADUsers.vbs

' ExportLockedoutADUsers.vbs
' Sample VBScript to Find and Export Locked-out AD users into CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim objFSO, objCSVFile
Dim lockoutFlag
Const Flag_LOCKOUT = 16
' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of getting from "defaultNamingContext"
' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

' Filter to list locked-out user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(SAMAccountType=805306368)(LockoutTime>=1))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ",msDS-User-Account-Control-Computed;subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

' Here, I have given CSV file path as "ADLockedUsers.csv", this will create ADUsers.csv file
' where you placed and execute this VB Script file. You can give your own file path
' like "C:\Users\Administrator\Desktop\ADLockedUsers.csv"

Set objCSVFile = objFSO.CreateTextFile("ADLockedUsers.csv", _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

' Ensure the user is still in locked-out state by checking UF_LOCKOUT flag
   ' in the msDS-User-Account-Control-Computed attribute
      
     lockoutFlag = adoRecordset.Fields("msDS-User-Account-Control-Computed").Value

    If (lockoutFlag and Flag_LOCKOUT) Then

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    End If
    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Active Directory Locked-Out User properties are exported successfully as CSV File

Export Locked-Out AD Users From Specific OU to CSV using VBScript

1. Copy the below example vbscript code and paste it in notepad or a vbscript editor.
2. Change the value for 'varBaseDN' into your own OU's DN .
3. Save the file with a .vbs extension, for example: ExportLockedoutADUsersFromOU.vbs
4. Double-click the vbscript file (or Run this file from command window) to export Locked-Out AD users into csv file.

 Click to get vbscript source code as a file Download ExportLockedoutADUsersFromOU.vbs

' ExportLockedoutADUsersFromOU.vbs
' Sample VBScript to Export Locked-out AD users From Specific OU into CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim strQuery, adoRecordset
Dim objFSO, objCSVFile
Dim lockoutFlag
Const Flag_LOCKOUT = 16
' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' varBaseDN is the OU DN for AD Serach Scope, you can give your own OU's Distinguished Name here.
varBaseDN = "<LDAP://OU=London,DC=Work2008,DC=Local>"

' Filter to list locked-out user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(SAMAccountType=805306368)(LockoutTime>=1))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ",msDS-User-Account-Control-Computed;subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

' Here, I have given CSV file path as "ADLockedUsers.csv", this will create ADUsers.csv file
' where you placed and execute this VB Script file. You can give your own file path
' like "C:\Users\Administrator\Desktop\ADLockedUsers.csv"

Set objCSVFile = objFSO.CreateTextFile("ADLockedUsers.csv", _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

' Ensure the user is still in locked out state by checking UF_LOCKOUT flag
   ' in the msDS-User-Account-Control-Computed attribute
      
     lockoutFlag = adoRecordset.Fields("msDS-User-Account-Control-Computed").Value

    If (lockoutFlag and Flag_LOCKOUT) Then

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    End If
    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' AD Locked-Out Users properties are exported successfully as CSV File


Export Locked-Out AD users to CSV file by dynamic CSV path using VBScript

1. Copy the below example vbscript code and paste it in notepad or a vbscript editor.
2. Save the file with a .vbs extension, for example: ExportLockedoutADUsersbyDynamicPath.vbs
3. Double-click the vbscript file (or Run this file from command window) to export Locked-out AD users.
4. Give the CSV file path to save locked out user attributes and click OK to proceed.

VBScript Export Locked-Out AD User Accounts into CSV file


Click to get vbscript code as a file Download ExportLockedoutADUsersbyDynamicPath.vbs

' ExportLockedoutADUsersbyDynamicPath.vbs
' Sample VBScript to Find and Export Locked-out AD users into CSV file
' by dynamically asking CSV file path from User.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim objFSO, objCSVFile
Dim csvFilePath 
Dim lockoutFlag
Const Flag_LOCKOUT = 16
' Asks CSV File path from user to save new file.
Do
   csvFilePath = InputBox ("Please enter CSV file path.- Ex: C:\ADUsers.csv")
   If csvFilePath= "" then
      Msgbox "No file path entered"
   end if
Loop Until csvFilePath <> ""

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of getting from "defaultNamingContext"
' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

' Filter to list locked-out user objects.
varFilter = "(&(objectCategory=person)(objectClass=user)(SAMAccountType=805306368)(LockoutTime>=1))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ",msDS-User-Account-Control-Computed;subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objCSVFile = objFSO.CreateTextFile(csvFilePath , _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

' Ensure the user is still in locked out state by checking UF_LOCKOUT flag
   ' in the msDS-User-Account-Control-Computed attribute
      
     lockoutFlag = adoRecordset.Fields("msDS-User-Account-Control-Computed").Value

    If (lockoutFlag and Flag_LOCKOUT) Then

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    End If
    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Locked-Out AD User properties are exported successfully as CSV File


Exported CSV File Output of Locked-Out AD Users:

VBScript to Find Locked Out AD Users

Saturday, 15 March 2014

VBScript to Export AD users to CSV file

In this article I am going write VBScript code to Find and Export Active Directory user's properties into CSV file and Search AD users by LDAP filter and Export to CSV file.

Summary:


VBScript to Find and Export Active Directory Users to CSV file

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Here, I have given CSV file path as "ADUsers.csv", this will create ADUsers.csv file where you placed and execute this VB Script file. You can give your own file path like "C:\Users\Administrator\Desktop\ADUsers.csv"
3. Save the file with a .vbs extension, for example: ExportADUsers.vbs
4. Double-click the VBScript file (or Run this file from command window) to Export AD users into csv file.

 Click to get vbscript source code as a file Download ExportADUsers.vbs

' ExportADUsers.vbs
' Sample VBScript to Find and Export AD users into CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim objFSO, objCSVFile

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of 
' getting from "defaultNamingContext"
' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

' Filter for user objects.
varFilter = "(&(objectCategory=person)(objectClass=user))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

' Here, I have given CSV file path as "ADUsers.csv", this will create ADUsers.csv file
' where you placed and execute this VB Script file. You can give your own file path
' like "C:\Users\Administrator\Desktop\ADUsers.csv"

Set objCSVFile = objFSO.CreateTextFile("ADUsers.csv", _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Active Directory User properites are exported Successfully as CSV File

VBScript to Export AD Users to CSV file from Specific OU (Organization Unit)

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for 'varBaseDN'  into your own OU's DN .
3. Save the file with a .vbs extension, for example: ExportADUsersFromOU.vbs
4. Double-click the VBScript file (or Run this file from command window) to Export AD users into csv file.

 Click to get vbscript source code as a file Download ExportADUsersFromOU.vbs

' ExportADUsersFromOU.vbs
' Sample VBScript to Find and Export AD users into CSV file from Specific OU .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, strQuery, adoRecordset
Dim objFSO, objCSVFile

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

' varBaseDN is the OU DN for AD Serach Scope, you can give your own OU's Distinguished Name here.

varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=Com>"


' Filter for user objects.
varFilter = "(&(objectCategory=person)(objectClass=user))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

' Here, I have given CSV file as "ADUsers.csv", this will create ADUsers.csv file
' where you placed and execute this VB Script file. You can give your own file path
' like "C:\Users\Administrator\Desktop\ADUsers.csv"

Set objCSVFile = objFSO.CreateTextFile("ADUsers.csv", _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Active Directory User properites are exported Successfully as CSV File

Search and Filter AD users by Department and Export to CSV file in VBScript

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for 'varSearchDept' from "Admin" to your own search word.
3. Save the file with a .vbs extension, for example: SearchAndExportADUsers.vbs
4. Double-click the VBScript file (or Run this file from command window) to Export AD users into csv file.

 Click to get vbscript source code as a file Download SearchAndExportADUsers.vbs

' SearchAndExportADUsers.vbs
' Sample VBScript to Search and Filter AD users and Export into CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim varSearchDept
Dim objFSO, objCSVFile

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of getting from "defaultNamingContext"
' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

varSearchDept ="Admin"

' Filter AD user by department "Admin", you can give your own search or filter value.
varFilter = "(&(objectCategory=person)(objectClass=user)(department="& varSearchDept &"))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

' Here, I have given CSV file as "ADUsers.csv", this will create ADUsers.csv file
' where you placed and execute this VB Script file. You can give your own file path
' like "C:\Users\Administrator\Desktop\ADUsers.csv"
 
Set objCSVFile = objFSO.CreateTextFile("ADUsers.csv", _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Active Directory User properites are exported Successfully as CSV File


VBScript to Export Active Directory Users to CSV file by dynamic CSV file path

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example: ExportADUsersbyDynamicPath.vbs
3. Double-click the VBScript file (or Run this file from command window) to Export AD users.
4. Give the CSV file to save Exported AD User attributes and Click OK to proceed.

VBScript Export AD users into CSV file


Click to get vbscript code as a file Download ExportADUsersbyDynamicPath.vbs

' ExportADUsersbyDynamicPath.vbs
' Sample VBScript to Export AD users into CSV file by dynamic CSV file path .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

' Initialize required variables.
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset
Dim csvFilePath
Dim objFSO, objCSVFile

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Asks CSV File path from user to save new file.
Do
   csvFilePath = InputBox ("Please enter CSV file path.- Ex: C:\ADUsers.csv")
   If csvFilePath= "" then
      Msgbox "No file path entered"
   end if
Loop Until csvFilePath <> ""

' Search entire Active Directory domain.
Set objRootDSE = GetObject("LDAP://RootDSE")

varDNSDomain = objRootDSE.Get("defaultNamingContext")
varBaseDN = "<LDAP://" & varDNSDomain & ">"

' varBaseDN is Domain DN, you can give your own OU DN instead of getting from "defaultNamingContext"

' like varBaseDN = "<LDAP://OU=TestOU,DC=Domain,DC=com>" 

' Filter for user objects.
varFilter = "(&(objectCategory=person)(objectClass=user))"

' Comma delimited list of attribute values to retrieve.
varAttributes = "name,samaccountname,distinguishedname,mail"

' Construct the LDAP syntax query.
strQuery = varBaseDN & ";" & varFilter & ";" & varAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 1000
adoCommand.Properties("Timeout") = 20
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objCSVFile = objFSO.CreateTextFile(csvFilePath , _ 
    ForWriting, True)

' Write selected AD Attributes as CSV columns(first line)
 objCSVFile.Write varAttributes 

 objCSVFile.Writeline ' New Line

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF

   ' Retrieve values and write into CSV file.

     objCSVFile.Write adoRecordset.Fields("name").Value & "," 
     objCSVFile.Write adoRecordset.Fields("samaccountname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("distinguishedname").Value & "," 
     objCSVFile.Write adoRecordset.Fields("mail").Value & ""
     objCSVFile.Writeline  ' New Line

    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

 objCSVFile.Close

' close ado connections.
adoRecordset.Close
adoConnection.Close

' Active Directory User properites are exported Successfully as CSV File


Exported CSV File Output:

VBScript to Export AD users to CSV file