Wednesday, 30 October 2013

How to validate Guid string in c#

Description:

This article contains the C# code snippets to validate Guid string in C# with Regular Expression and without Regular Expression.

Summary:

  1. Validate Guid string in .NET C# with Regular Expression
  2. Check and Validate Guid string in .NET C# without Regular Expression

Validate Guid string in .NET C# with Regular Expression

You can use this C# function to check whether the given Guid string is in valid Guid format or not.
public static bool IsGuid1(string guidString)
    {
        bool isValid = false;
        if (!string.IsNullOrEmpty(guidString))
        {
            Regex isGuid = 
                new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$"
                    ,RegexOptions.Compiled);

            if (isGuid.IsMatch(guidString))
            {
                isValid = true;
            }
        }
        return isValid;
    }

Check and Validate Guid string in .NET C# without Regular Expression

You can use this C# function to check whether the given Guid string is in valid Guid format or not without using Regular Expression which considers to be a fast method.
 public static bool IsGuid(string guidString)
    {
        // Length of a proper GUID, without any surrounding braces.
        const int len_without_braces = 36;

        // Delimiter for GUID data parts.
        const char delim = '-';

        // Delimiter positions.
        const int d_0 = 8;
        const int d_1 = 13;
        const int d_2 = 18;
        const int d_3 = 23;

        // Before Delimiter positions.
        const int bd_0 = 7;
        const int bd_1 = 12;
        const int bd_2 = 17;
        const int bd_3 = 22;

        if (guidString == null)
            return false;

        if (guidString.Length != len_without_braces)
            return false;

        if (guidString[d_0] != delim ||
            guidString[d_1] != delim ||
            guidString[d_2] != delim ||
            guidString[d_3] != delim)
            return false;

        for (int i = 0;
            i < guidString.Length;
            i = i + (i == bd_0 ||
                    i == bd_1 ||
                    i == bd_2 ||
                    i == bd_3
                    ? 2 : 1))
        {
            if (!IsHex(guidString[i])) return false;
        }

        return true;
    }

   private static bool IsHex(char c)
    {
        return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
    }

Thanks,
Morgan
Software Developer

Tuesday, 29 October 2013

Get Machine name from IP Address c#

Description:

This article contains the C# code snippets to get Hostname or Machine name from IP Address and get IP Address from Machine name/Hostname.

Summary:

  1. Get Machine name from IP Address in C#
  2. Get Machine name from IPAddress in Command Prompt
  3. Get IPAddress from Machine name in C#

Get Machine name from IP Address in C#

You can use this C# function to convert IP Address into Hostname in C#
private static string GetMachineNameFromIPAddress(string ipAdress)
        {
            string machineName = string.Empty;
            try
            {
                IPHostEntry hostEntry=Dns.GetHostEntry(ipAdress);

                machineName=hostEntry.HostName;
            }
            catch (Exception ex)
            {
                // Machine not found...
            }
            return machineName;
        }

Get Hostname from IP Address using cmd ping Command

You can get Machine name or Hostname from IP Address using the following command
ping -a 192.168.56.101


Get IPAddress from Machine name(Hostname) in C#

You can use this C# function to convert Hostname into IP Address in C#
private static string GetIPAddressFromMachineName(string machineName)
        {
            string ipAdress = string.Empty;
            try
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(machineName);

                IPAddress ip = ipAddresses[1];

                ipAdress = ip.ToString();
            }
            catch (Exception ex)
            {
                // Machine not found...
            }
            return ipAdress;
        }

Thanks,
Morgan
Software Developer

Event ID 5145 - Detailed File Share Auditing

Description:

   The Event ID 5145 is controlled by the security policy setting Detailed File Share Auditing which allows you to audit attempts to access files and folders on a shared folder. The Detailed File Share setting logs an event every time a file or folder is accessed and it includes detailed information about the permissions or other criteria used to grant or deny access.

Note: Event 5145 - Detailed File Share Auditing is available only from Windows 2008 R2 and later versions/Windows 7 and later versions.

Summary:


Event 5145 Sample Source

  This is the sample event (5145) source which I got while renaming(Rename Action) the New Text Document.txt file
Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          29/10/2013 1:43:34 PM
Event ID:      5145
Task Category: Detailed File Share
Keywords:      Audit Success
Computer:      myfileServer.myDomain.local
Description:
A network share object was checked to see whether client can be granted desired access.
 
Subject:
 Security ID:  myDomain\Administrator
 Account Name:  Administrator
 Account Domain:  myDomain
 Logon ID:  0x37d7f

Network Information: 
 Object Type:  File
 Source Address:  fe80::7053:e964:a753:6842
 Source Port:  32953
 
Share Information:
 Share Name:  \\*\share
 Share Path:  \??\C:\share
 Relative Target Name: Test\New Text Document.txt

Access Request Information:
 Access Mask:  0x110080
 Accesses:  DELETE
    SYNCHRONIZE
    ReadAttributes
    
Access Check Results:
 DELETE: Granted by D:(A;OICI;FA;;;WD)
    SYNCHRONIZE: Granted by D:(A;OICI;FA;;;WD)
    ReadAttributes: Granted by D:(A;OICI;FA;;;WD)    


Fine Share Path, Local Path and Source Machine Name

 Find Share Path of the Accessed File:

   In the event source you could see the fields
   Share Name: \\*\share
   Relative Target Name: Test\New Text Document.txt

  - now replace * value in  Share Name: by fileServerName --->\\myfileServer\share
and joining this value with Relative Target Name: will gives the complete share path of the changed file 

    Full share path: \\myfileServer\share\Test\New Text Document.txt 

 Find Local Path of the Accessed File:

    In the event source you could see the field
    Share Path: \??\C:\share - here remove the string \??\  and joining this value with Relative Target      Name: will gives the complete local path of the changed file

     Local path: C:\shareTest\New Text Document.txt 

 Find user's Source Machine name:

    One more beauty of this event (5145) is, you can find user's source machine, it means, from which machine the user has accessed this file server .

   You can see the field      - Source Address: fe80::7053:e964:a753:6842, this is the address of the client computer from which the user accessed this file server.

   You can easily find client machine's name from Source Address by pinging with the following command
   ping -a  fe80::7053:e964:a753:6842

How to enable Detailed File Share Auditing (Event ID 5145) 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 success event (Event ID 5145) of Detailed File Share Auditing by using following command
Auditpol /set /subcategory:"Detailed File Share" /success:enable
You can enable failure audit event (Event ID 5145) of Detailed File Share Auditing by using following command
Auditpol /set /subcategory:"Detailed File Share" /failure:enable

How to enable Event ID 5145 - Detailed File Share Auditing through Group Policy

    When you enable this setting through Auditpol command, it will apply only to the local system, however, if you want to enable this setting on all the File Servers in entire Active Directory domain, you need to apply this setting via Group Policy.

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

2. Expand the domain node, select and right-click on the OU which contains all the file servers, then click Create a GPO in this domain, and link it here...


Event ID 5145 - Detailed File Share Auditing


3. Type the New GPO name and click OK (Ex: FileSharePolicy)

Event 5145 - Detailed File Share Auditing


4. Right-click on the newly created GPO, then click Edit

Enable Event 5145 - Detailed File Share Auditing


5. Expand the 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 Object Access (Audit Polices->Object Access), then select the Setting
Audit Detailed File Share Audit


Enable Event 5145 - Detailed File Share Auditing


7. Double-click on  Audit Detailed File Share Audit, then check Success and Failure settings, and then click the button Apply.

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


How to disable/stop Event 5145-Detailed File Share Auditing

    You can disable audit success event (Event ID 5145) of Detailed File Share Auditing by using following command
Auditpol /set /subcategory:"Detailed File Share" /success:disable
You can disable failure audit event (Event ID 5145) of Detailed File Share Auditing by using following command
Auditpol /set /subcategory:"Detailed File Share" /failure:disable
You can also stop this event by removing the success and failure setting from the GPO in the setting path  Computer Configuration->Polices->Windows Settings->Security Settings->Advanced Audit Policy Configuration->Audit Polices->Object Access->Audit Detailed File Share Audit.

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

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

Thanks,
Morgan
Software Developer

Monday, 28 October 2013

Event Id 1000 faulting application flashplayerupdateservice exe

Description:

I am getting this Application Error every day with the event id 1000. In some of the day, my system getting restarted unexpectedly. Initially I though regular system update might be the cause for this restart. But since it is being happened regularly I started to analyze event log and got this event 1000

Event 1000 Source:

This is source of the error which I got from the event log

Log Name:      Application
Source:        Application Error
Date:          10/28/2013 7:50:01 PM
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      hp-PC
Description:
Faulting application name: FlashPlayerUpdateService.exe, version: 11.6.602.180, time stamp: 0x51a4ab8c
Faulting module name: ntdll.dll, version: 6.1.7600.16385, time stamp: 0x4a5bdadb
Exception code: 0xc0000005
Fault offset: 0x000335d3
Faulting process id: 0x830
Faulting application start time: 0x01ced3e8c925e56b
Faulting application path: C:\Windows\system32\Macromed\Flash\FlashPlayerUpdateService.exe
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: 077be1cf-3fdc-11e3-bc53-08002700f4a4

After I have analyzed and googled for some time, got the following useful links regarding the application error event 1000

http://forums.adobe.com/message/4589191
http://community.spiceworks.com/windows_event/show/13-application-error-1000
http://www.computerforum.com/125002-applications-crash-event-id-1000-a.html
http://support.microsoft.com/kb/914048
http://www.eventid.net/display-eventid-1000-source-Application%20Error-eventno-1475-phase-1.htm

Saturday, 26 October 2013

How to configure SQL Server Authentication mode SQL Server

Description:

In this article I am going to explain about how to enable or configure SQL Server Authentication mode or Mixed mode Authentication in SQL Server.

Steps to Enable SQL Server and Windows Authentication mode via SQL Management Studio

1. Open the SQL Server Management Studio with an elevated privilege(Run as administrator).

How to enable SQL Server Authentication mode in SQL Server

2. Select  SQL Server instance or type the instance name (machine\sqlinstancename).  then click the Connect button.

How to enable SQL Server Authentication and Windows Authentication mode in SQL Server


3. Right-click on the connected server instance, and click Properties.

How to enable SQL Server Authentication mode in SQL Server 2008 R2

4. Navigate to the Security page, select SQL Server and Windows Authentication mode, and click OK

How to enable SQL Server Authentication mode in SQL Server 2008 R2


5. We need to Restart corresponding SQL Server service to take effect this change immediately.

How to enable SQL Server Authentication mode in SQL Server 2008 R2





Thanks,
Morgan
Software Developer

Friday, 25 October 2013

Add Environment Variable via Group Policy

Description:

In this article I am going to explain about how to Create or Add System Environment variable and User Environment variable via Group Policy.

Summary:

  1. Add System Environment variable through group policy
  2. Add User Environment variable through group policy

Steps to Add System Environment variable through GPO

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

2. Expand the domain node,  Right-Click on the OU that contains computer objects which you are going to add Environment variable and click Create a GPO in this domain, and Link it here...

Add Environment Variable via GPO


3. Type the new gpo name in the opened text box, and click OK.

Add Environment Variable via GPO

4. Right-click on the newly created GPO, and click Edit.


Add Environment Variable via Group Policy


5. Expand the Computer Configuration and got to the node Environment (Computer Configuration->Preferences->Windows Settings->Environment).

6. Right-click on the node Environment, click New->Environment Variable.

7. Ensure that the radio button System Variable is checked, fill the text box values for Name and Value, and click Apply.


Add Environment Variable through Group Policy


8. Now, you have created new Environment variable using GPO for the computers which are inside the OU Testing Computers. You can also limit the scope of this Environment Variable by Security Filtering.

9. Click on the tab Scope,  go to the section Security Filtering, now Remove the Authenticated Users entry

Add Environment Variable through Group Policy


10. Click Add button, and Click the button Object Types in the opened dialog, and select Computers type and click OK

Add Environment Variable through Group Policy


11. Now select the computer which you want add Environment variables through this GPO, and click OK. In this way you can add computers one-by-one to apply this gpo.

Add Environment Variable through GPO

12. Now you have successfully created the Environment Variable using Group Policy, to see the value, update the GPO by running the command GPUpdate/Force.

13. Logoff the machine and Login again to see newly created Environment Variable

14. Run the command set SystemType to check the newly created Environment Variable

Add User Environment Variable through GPO



Steps to Create User Environment variable through GPO

1. Create the new GPO and link it the OU that contains the users which you are going to add new Environment Variable.

2. Right-Click on the GPO, and click Edit

3. Expand  User Configuration, and go to the node User Configuration ->Preference ->Windows Settings ->Environment. Right-Click on the node Environment, and Click New->Environment Variable.

4. Ensure the radio button User variable is checked, fill the values for Name and Value, and Click Apply

Set Environment Variable through Group Polciy


5. You can also limit the scope of this policy to the users only who are in the Security group TestingTeam by removing the Authenticated Users Entry in Security Filtering, and add the group TestingTeam.

Add Environment Variable through GPO


6. Now you have successfully created the User Environment Variable using Group Policy, to see the value, update the GPO by running the command GPUpdate/Force.

7. Logoff the machine and Login again to see the newly created Environment Variable.

Now, you have successfully created the GPO to Create Environment Variable via Group Policy

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

Related Articles:

- How to Pin a Program to Start menu via Group Policy
Create Folder on Desktop via GPO
Pin Program to Taskbar via Group Policy
Add desktop shortcut icon through Group Policy
Add start menu shortcut via Group Policy

Thursday, 24 October 2013

Create new Active Directory User in C#

Description:

  In this article, I am going to write C# code snippets to create new Active Directory user and Bulk AD users in different methods.

Summary:

  1. Create new Active Directory user in C# using UserPrincipal  
  2. Create new user in Active Directory using C# with DirectoryEntry
  3. Create Bulk AD Users in C#
  4. Create Bulk AD Users From CSV File in C#

Create new Active Directory user in C# using UserPrincipal:

To use this class, you need to add reference System.DirectoryServices.AccountManagement.dll
PrincipalContext ouContex = new PrincipalContext(ContextType.Domain, 
                                                 "TestDomain.local", 
                                                 "OU=TestOU,DC=TestDomain,DC=local");

  try
   {
     UserPrincipal up = new UserPrincipal(ouContex);
     up.SamAccountName = "NewTestUser";
     up.SetPassword("password");
     up.Enabled = true;
     up.ExpirePasswordNow();
     up.Save();
   }
   catch (Exception ex)
   {
   }


Create new user in Active Directory using C# with DirectoryEntry:

To use this class, you need to add reference System.DirectoryServices.dll
DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");

    try
    {
        DirectoryEntry childEntry = ouEntry.Children.Add("CN=NewTestUser", "user");
        childEntry.CommitChanges();
        ouEntry.CommitChanges();
        childEntry.Invoke("SetPassword", new object[] { "password" });
        childEntry.CommitChanges();
    }
    catch (Exception ex)
    {
    }

Create Bulk AD Users in C#:

DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");

    for (int i = 0; i < 10; i++)
    {
        try
        {
            DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user");
            childEntry.CommitChanges();
            ouEntry.CommitChanges();
            childEntry.Invoke("SetPassword", new object[] { "password" });
            childEntry.CommitChanges();
        }
        catch (Exception ex)
        {

        }
    }

Create Bulk AD Users From CSV File in C#:

Consider the CSV file All_users.csv which contains set of new AD Users to create with the column header samAccountName.

Create Bulk AD Users from CSV file using Powershell Script

We are using the Visual basic class TextFieldParser to read CSV file, so we need to add reference dll Microsoft.VisualBasic.

static void CreatBulkADUsersFromCSVFile()
    {
        string csvFilePath=@"C:\Users\Admin\Desktop\All_users.CSV";

        using (TextFieldParser csvReader = new TextFieldParser(csvFilePath))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;

            // reading column fields 
            string[] colFields = csvReader.ReadFields();

            int index_samaccountName = colFields.ToList().IndexOf("samAccountName");

            while (!csvReader.EndOfData)
            {
                // reading user fields 
                string[] fieldData = csvReader.ReadFields();

                DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOu,DC=YourDomain,DC=local");

                try
                {
                    DirectoryEntry childEntry = ouEntry.Children.Add("CN=" + fieldData[index_samaccountName], "user");
                    childEntry.CommitChanges();
                    ouEntry.CommitChanges();
                    childEntry.Invoke("SetPassword", new object[] { "password" });
                    childEntry.CommitChanges();
                }
                catch (Exception ex)
                {
                }
            }
        }
    }

Thanks,
Morgan
Software Developer

Wednesday, 23 October 2013

Enable Active Directory user account via VBScript

Description:

In this article, I am going to explain and give VBScript source code to Enable Active Directory user account via VBScript using user's objectguid, samAccountName and distinguishedname and also Enable Bulk AD Users from CSV file using VBScript.

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

Summary:


Enable Active Directory user using VBScript with user's DN

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserDN with your own user's DN which you are going to enable.
3. Save the file with a .vbs extension, for example: Enable-AD-User.vbs
4. Double-click the vb script file (or Run this file from command window) to enable AD user.

Click to get VBScript source code as a file Download Enable-AD-User.vbs
' Enable-AD-User.vbs
' Sample VBScript to enable Active Directory user
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserDN
Dim objUser 

strUserDN= "CN=TestUser,OU=TestOU1,DC=MyDomain,DC=Com"
Set objUser = GetObject("LDAP://"& strUserDN) 
objUser.AccountDisabled = FALSE
objUser.SetInfo

MsgBox("AD user enabled successfully using VBScript code.")

WScript.Quit 

Enable AD user using VBScript with user's ObjectGUID


1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserGUID with your own user's ObjectGUID string which you are going to enable.
3. Save the file with a .vbs extension, for example: EnableADUserWithGUID.vbs
4. Double-click the vb script file (or Run this file from command window) to enable AD user. Click the following link to get VBScript source code as a file

Click  to get VBScript source code as a file Download EnableADUserWithGUID.vbs
' EnableADUserWithGUID.vbs
' Sample VBScript to enable AD user with ObjectGUID
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserGUID
Dim objUser 

strUserGUID= "A777394D-0B5C-4FD2-BDDC-B12DDFB570A4"
Set objUser = GetObject("LDAP://<guid="& struserguid&">")
objUser.AccountDisabled = FALSE
objUser.SetInfo

MsgBox("AD user enabled successfully using VBScript code.")

WScript.Quit 

Enable AD user using VBScript with user's samAccountName

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 samAccountName which you are going to enable.
3. Save the file with a .vbs extension, for example: EnableADUserWithsamAccountName.vbs
4. Double-click the vb script file (or Run this file from command window) to enable AD user.

Click to get VBScript source code as a file Download EnableADUserWithsamAccountName.vbs
' EnableADUserWithsamAccountName.vbs
' Sample VBScript to enable AD user .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset,strUserDN
Dim strSamAccountName,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 & ">"

strSamAccountName="Test"

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

' 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
    ' Retrieve values and display.
    strUserDN = adoRecordset.Fields("distinguishedname").value
    Set objUser = GetObject("LDAP://"& strUserDN) 
        objUser.AccountDisabled = FALSE
        objUser.SetInfo

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

  If strUserDN = "" then
      Msgbox "No user found with the name '"& strSamAccountName &"'"
    Else  Msgbox "The user '"& strSamAccountName &"' enabled successfully..."
   end if

' close ado connections.
adoRecordset.Close
adoConnection.Close

Enable AD user using VBScript with user's samAccountName 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: EnableADUserWithDynamicSamAccountName.vbs
3. Double-click the vb script file (or Run this file from command window) to enable AD user.
4. Enter the samAccountName of the user in the input text box and click OK to proceed.

Click to get VBScript code Download EnableADUserWithDynamicSamAccountName.vbs
' EnableADUserWithDynamicSamAccountName.vbs
' Sample VBScript to enable AD user .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset,strUserDN
Dim strSamAccountName,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 & ">"

' Asks samAccountName from user.
Do
   strSamAccountName = InputBox ("Please enter user's samAccountName")
   If strSamAccountName = "" then
      Msgbox "No samAccountName entered"
   end if
Loop Until strSamAccountName <> ""

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

' 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
    ' Retrieve values and display.
    strUserDN = adoRecordset.Fields("distinguishedname").value
    Set objUser = GetObject("LDAP://"& strUserDN) 
        objUser.AccountDisabled = FALSE
        objUser.SetInfo

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

  If strUserDN = "" then
      Msgbox "No user found with the name '"& strSamAccountName &"'"
    Else  Msgbox "The user '"& strSamAccountName &"' enabled successfully..."
   end if

' close ado connections.
adoRecordset.Close
adoConnection.Close

Enable Bulk AD users From CSV File 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: EnableBulkADUsersFromCSV.vbs
3. Change the CSV file path C:\Users\Administrator\Desktop\All_Users.csv with your own file path.
4. Double-click the VBScript file (or Run this file from command window) to enable Bulk AD users from CSV file.

Note: Your CSV file (All_Users.csv)  should contains the column objectguid as a first column, otherwise you need to change the index value 0 to other value here... csvUserFields(0)... which depends on your column index of objectguid in CSV file

Bulk AD users Enable From CSV File using VBScript

Click to get VBScript code Download EnableBulkADUsersFromCSV.vbs
' EnableBulkADUsersFromCSV.vbs
' Sample VBScript to Enable AD Users from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit

Dim strUserGUID,objUser 

' Variables needed for CSV File Information
Dim varFileName,objFSO,objFile,csvUserFields
Const ForReading = 1

' Specify the csv file full path.
varFileName = "C:\Users\Administrator\Desktop\All_Users.csv"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(varFileName, ForReading)

' Read the first line - csv columns -not needed for our proceess
objFile.ReadLine

' Skip the error if the user doesn't exist.....
on error resume next

' Read the file and create new user.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    csvUserFields = Split(objFile.ReadLine,",")

' All_Users.csv file should contains the column objectguid as first column
' Otherwise you need change the index value 0 to other value here...csvUserFields(0)...
' which depends on your column index of objectguid in CSV file.

     strUserGUID =  csvUserFields(0)
 Set objUser = GetObject("LDAP://<GUID="& strUserGUID &">")
     objUser.AccountDisabled = FALSE
     objUser.SetInfo
Loop

MsgBox("Bulk AD Users enabled from CSV file using VBScript.")

WScript.Quit 

Tuesday, 22 October 2013

The directory is not empty cannot delete error

Description:

I got error The directory is not empty cannot delete while deleting some folders in my Windows 8 machine. but when check the folder, I don't find any suspected files regarding error this error. I have deleted many times this kind of folders with lot files inside, but today only I got this error.

Solution - The directory is not empty cannot delete:

After I have googled and analyzed, I noticed the reason for this error is due to Hidden files which are inside the folders.

try to delete folder with this command

rmdir /s C:\Users\YourFolder\folder
- or -
rmdir /s/q C:\Users\YourFolder\folder

Solution - The directory is not empty cannot delete in C# :

If you got this error while deleting folder from C# code you need to use following code to set folder attributes into Normal.

File.SetAttributes(target_dir, FileAttributes.Normal);
Directory.Delete(target_dir, false);

Useful References:

http://www.codingforums.com/showthread.php?t=217642

http://forums.techguy.org/all-other-software/1019285-cannot-delete-folder.html

http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true


Thanks,
Morgan
Software Developer

Find AD user location in VBScript by samAccountName

In this article I am going give the VBScript code to find Active Directory user's location (distinguishedname) by their samAccountName.

Summary:

 1. Find Active Directory User Location by samAccountName
 2. Find Active Directory User with Dynamic input of samAccountName

Find Active Directory User Location by samAccountName:

1. Copy the below example VBScript code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName if you want to give your own name otherwise simply leave it.
3. Save the file with a .vbs extension, for example: FindADUser.vbs
4. Double-click the VBScript file (or Run this file from command window) to Find AD user.

 Click to get VBScript source code as a file Download FindADUser.vbs
' FindADUser.vbs
' Sample VBScript to find AD object .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset, strName, strDN
Dim varSearchName

' 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 & ">"

varSearchName="Test"

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

' 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
    ' Retrieve values and display.
    strName = adoRecordset.Fields("samaccountname").Value
    strDN = adoRecordset.Fields("distinguishedname").value
    Wscript.Echo "Name: " & strName & "; Location: " & strDN
    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

  If strName= "" then
      Msgbox "No user found with the name '"& varSearchName &"'"
   end if

' close ado connections.
adoRecordset.Close
adoConnection.Close

Find Active Directory User with Dynamic input of samAccountName:

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: FindADUserWithDynamicName.vbs
3. Double-click the VBScript file (or Run this file from command window) to Find AD user.
4. Give the samAccountName of user which you want find and Click OK to proceed.

Click to get VBScript code as a file Download FindADUserWithDynamicName.vbs
' FindADUserWithDynamicName.vbs
' Sample VBScript to find AD object with dynamic samaccountname.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim objRootDSE, varDNSDomain, strQuery, adoRecordset, strName, strDN
Dim varSearchName

' 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 & ">"

' Asks samAccountName from user.
Do
   varSearchName = InputBox ("Please enter user's samAccountName")
   If varSearchName = "" then
      Msgbox "No samAccountName entered"
   end if
Loop Until varSearchName <> ""


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

' 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
    ' Retrieve values and display.
    strName = adoRecordset.Fields("samaccountname").Value
    strDN = adoRecordset.Fields("distinguishedname").value
    Wscript.Echo "Name: " & strName & "; Location: " & strDN
    ' Move to the next record in the recordset.
    adoRecordset.MoveNext
Loop

  If strName= "" then
      Msgbox "No user found with the name '"& varSearchName &"'"
   end if

' close ado connections.
adoRecordset.Close
adoConnection.Close

The type initializer for 'MyClass' threw an exception

Description:

   In this article I am going to explain about what would be the cause for the error The type initializer for 'MyClass' threw an exception.

Summary:

   I got the error The type initializer for threw an exception while debugging my C# project in Visual Studio. When I google about the error The type initializer for threw an exception I got more suggestion to resolve this error. most of the suggestions are asked me to see what is the Inner Exception message of this error, I got the error message Value cannot be null. Parameter name: string in inner exception. The finally I found the following solution for my issue.

Solution -The type initializer for threw an exception:

Finally I found reason for this issue is AppConfig settings of my project. Yes, I have two C# projects, Project1 and Project2.

 Project1 is contains the Static class MyDetails
public static MyDetails
{
  public static int _LogLevel = Int32.Parse(ConfigurationManager.AppSettings["LogLevel"])

  public static GetData()
   {
     ----code----
     ----code----
   }
}
I have following appConfig settings in Project1

<appSettings>
    <add key="LogLevel" value="5"/>
</appSettings>

 The function MyDetails.GetData() is being called From Project2 which is the project I am debugging now. Since Project2  is the target project,  the line ConfigurationManager.AppSettings["LogLevel"] will try to read setting LogLevel from Project2. but LogLevel setting is only available in Project1. so, we need to add appsettings in Project2.

The issue The type initializer for threw an exception has been solved after adding  the folowing appsettings in appConfig of Project2,

<appSettings>
    <add key="LogLevel" value="5"/>
</appSettings>



Thanks,
Morgan
Software Developer

Saturday, 19 October 2013

Import CSV File Into SQL Server Using SQL Bulk Copy

Description:

This article contain C# code example to import CSV file data into DataTable and insert bulk records into SQL server database using SQL Bulk Copy.

Summary:

1. Import CSV file into DataTable C#.
2. Insert Bulk records into SQL Server using SQL Bulk Copy.

Import CSV file into DataTable C#

 We can read data from CSV file in many of custom ways. In this article, I am going to write the C# code to read data from CSV file into .NET DataTable by using TextFieldParser. don't try to search this class in C# library because which is not available in C#. TextFieldParser is the Visual basic class. So we need to add reference dll Microsoft.VisualBasic.

  • Open Visual Studio
  • Go to File ->New ->Project.
  • Then go to Visual C# ->Windows and select Console Application
  • Rename the project name as ReadCSVFile.
  • Right-click the Reference, click Add Reference,select Microsoft.VisualBasic, and click OK button


You can use the following code example to read data from CSV file in C# and pass the DataTable object to the function InsertDataIntoSQLServerUsingSQLBulkCopy  which is available in below section (Insert Bulk records into SQL Server using SQL Bulk Copy).


using System;
using System.Data;
using Microsoft.VisualBasic.FileIO;

namespace ReadDataFromCSVFile
  {
    static class Program
      {
        static void Main()
        {
            string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";
            DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
            Console.WriteLine("Rows count:" + csvData.Rows.Count);            
            Console.ReadLine();
        }
    private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();
            try
            {
              using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                 {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    string[] colFields = csvReader.ReadFields();
                    foreach (string column in colFields)
                    {
                        DataColumn datecolumn = new DataColumn(column);
                        datecolumn.AllowDBNull = true;
                        csvData.Columns.Add(datecolumn);
                    }
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }
                        csvData.Rows.Add(fieldData);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return csvData;
        }
      }
    }

Insert Bulk Records into SQL Server using SQL Bulk Copy

   You can import CSV File into C# DataTable using the function ReadDataFromCSVFile which is available in above section (Import CSV file into DataTable C#). You can pass this databale object to the following function to insert into SQL Server using SQL Bulk Copy.

            // Copy the DataTable to SQL Server using SqlBulkCopy
function static void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
{
   using(SqlConnection dbConnection = new SqlConnection("Data Source=.\SQLEXPRESS; Initial Catalog=MorganDB; Integrated Security=SSPI;"))
        {
          dbConnection.Open();
          using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
            {
                s.DestinationTableName = "Your table name";

                foreach (var column in csvFileData.Columns)
                s.ColumnMappings.Add(column.ToString(), column.ToString());

                s.WriteToServer(csvFileData);
             }
         }
  }


Related Articles:

How to read data from csv file in c# 
Bulk Insert into SQL Server using SqlBulkCopy in C#
Convert DateTime to Ticks and Ticks to DateTime in C#
Convert Object To Byte Array and Byte Array to Object in C#
Add or Remove programs using C# in Control Panel 
Show balloon tooltip c#


Thanks,
Morgan
Software Developer

Friday, 18 October 2013

Auditpol Command Examples to Change Security Audit settings

Description

  This article provides the step-by-step details about Auditpol command usage and examples to get and set Security Audit settings as category and sub category level (Advanced Audit Configuration).

Usage of Auditpol command:

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

Usage: AuditPol command [<sub-command><options>]

Commands (only one command permitted per execution)
  /?               Help (context-sensitive)
  /get            Displays the current audit policy.
  /set            Sets the audit policy.
  /list            Displays selectable policy elements.
  /backup     Saves the audit policy to a file.
  /restore      Restores the audit policy from a file.
  /clear           Clears the audit policy.
  /remove          Removes the per-user audit policy for a user account.
  /resourceSACL    Configure global resource SACLs

Auditpol Command Examples:

Lists all the settings
Auditpol /get /category:*
Lists only the Account Management category settings.
Auditpol /get /category:"Account Management"
Lists only the User Account Management subcategory setting.
Auditpol /get /subcategory:"User Account Management" 
Set the  Account Management category setting as success.
Auditpol /set /category:"Account Management" /success:enable
Set the  Account Management category setting as failure.
Auditpol /set /category:"Account Management" /failure:enable
Disable/Remove success setting of the  Account Management category.
Auditpol /set /category:"Account Management" /success:disable
Disable/Remove failure setting of the  Account Management category.
Auditpol /set /category:"Account Management" /failure:disable
Set only the subcategory setting User Account Management as success.
Auditpol /set /subcategory:"User Account Management" /success:enable 
Set only the subcategory setting User Account Management as failure.
Auditpol /set /subcategory:"User Account Management" /failure:enable 
Lists Detailed Tracking category settings only for the user Administrator.
Auditpol /get /user:Administrator /category:"Detailed Tracking" 
Set Detailed Tracking category setting as success only for the user Administrator.
Auditpol /set /user:Administrator /category:"Detailed Tracking" /success:enable 



Thanks,
Morgan
Software Developer

Event ID 1059 - The DHCP service failed to see a directory server for authorization

Description:

This article explains the possible cause of the error event Event 1059 and gives solution to resolve this issue, also gives the useful reference links to solve issue. 

Event 1059 Source:

Log Name:      System
Source:        Microsoft-Windows-DHCP-Server
Date:          10/18/2013 10:13:39 AM
Event ID:      1059
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      myPC.myDomain.in
Description:
The DHCP service failed to see a directory server for authorization.

Event 1059 Source Image:


Cause and Solution for Event 1059:

After I have googled and analyzing this issue in my work environment found the 1046 also logged followed by event 1059. and noticed the service Remote Procedure Call (RPC) has been stopped, restarting this service solved will solve the DHCP related issues.

 Reference links about Event ID 1059

1. http://technet.microsoft.com/en-us/library/cc774849(v=ws.10).aspx
2. http://social.technet.microsoft.com/Forums/windowsserver/en-US/38812bd4-2b52-4e5b-ae8f-a74554d23da4/dhcp-server-eventid-1059
3. http://technet.microsoft.com/en-us/library/cc726867(v=ws.10).aspx
4. http://www.petri.co.il/forums/showthread.php?t=6323

Thanks, if you find any other useful information, please share with us


Related Articles:

Event ID 4656 - Repeated Security Event log - PlugPlayManager
Event ID 1046 - DHCP Server
- Event ID 1000 -The remote procedure call failed in Sql Server Configuration manager
Event 4624 null sid - Repeated security log
Event ID 1014 Name resolution for the name cyber-mind.info timed out after none of the configured DNS servers responded
Event ID 7036 service entered the stopped state - Service Control Manager
Event ID 5156 Filtering Platform Connection - Repeated security log


Thursday, 17 October 2013

Event ID 1046 - DHCP Server

Description:

This article explains the possible cause of the error event Event 1046 and gives solution to resolve this issue, also gives the useful reference links to solve issue. 

Event 1046 Source:

Log Name:      System
Source:        Microsoft-Windows-DHCP-Server
Date:          10/18/2013 10:12:39 AM
Event ID:      1046
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      myPC.myDomain.in
Description:
The DHCP/BINL service on the local machine, belonging to the Windows Administrative domain myDomain.in, has determined that it is not authorized to start.  It has stopped servicing clients.  The following are some possible reasons for this: 
 This machine is part of a directory service enterprise and is not authorized in the same domain.  (See help on the DHCP Service Management Tool for additional information). 

 This machine cannot reach its directory service enterprise and it has encountered another DHCP service on the network belonging to a directory service enterprise on which the local machine is not authorized. 

 Some unexpected network error occurred.

Event 1046 log image:

Event ID 1046 - DHCP Server

Cause and Solution for Event 1046:

 After I have googled and analyzing this issue in my work environment  found the service Remote Procedure Call (RPC) has been stopped, restarting this service solved will solve the DHCP related issues.

Reference links about Event ID 1046

1. http://technet.microsoft.com/en-us/library/cc726914(v=ws.10).aspx
2. http://www.microsoft.com/technet/support/ee/transform.aspx?ProdName=Windows+Operating+System&ProdVer=5.2&EvtID=1046&EvtSrc=DHCPServer
3. http://social.technet.microsoft.com/Forums/windowsserver/en-US/babd49b5-da0d-4838-9fcd-2591efa17dc5/unable-to-authorize-dhcp-server-event-id-1046-1059?forum=winserverNIS
4. http://www.eventid.net/display-eventid-1046-source-DhcpServer-eventno-2944-phase-1.htm


Thanks, if you find any other useful information, share with us

Related Articles:

Event ID 4656 - Repeated Security Event log - PlugPlayManager
Event ID 1000 -The remote procedure call failed in Sql Server Configuration manager
Event 4624 null sid - Repeated security log
Event ID 1014 Name resolution for the name cyber-mind.info timed out after none of the configured DNS servers responded
Event ID 7036 service entered the stopped state - Service Control Manager
Event ID 5156 Filtering Platform Connection - Repeated security log
Event ID 1059 - The DHCP service failed to see a directory server for authorization


Create Bulk AD users from CSV file using VBScript

Description

    This article contains the VBScript code to Create Bulk Active Directory users from CSV file and also contain the VBScript code to create Bulk AD Users from CSV file with dynamic file path input.

Related Article: Powershell Script to Create Bulk AD Users from CSV

Summary

  1. Create Bulk AD users from CSV file using VB Script.
  2. Create Bulk AD users from CSV file using VB Script with Dynamic file path.

Create Bulk AD users from CSV File using VB Script

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: CreateBulkADUsers.vbs
3. Change the CSV file path C:\Users\Administrator\Desktop\NewUsers.csv with your own file path.
4. Change the domain name workdomain.local to your own domain name.

Note:Your CSV file should contain the columns samAccount, givenName and sn as first three columns

Create Bulk Active Directory users from CSV File in VB Script

5. Double-click the vb script file (or Run this file from command window) to create Bulk Active Directory users from CSV file.

Click to get VBScript source code as file Download CreateBulkADUsersFromCSVFile.vbs 
' CreateBulkADUsersFromCSVFile.vbs
' Sample VBScript to create a AD Users from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit 
 
' Variables needed for LDAP connection 
Dim objRootLDAP 
Dim objContainer 

' Variables needed for CSV File Information
Dim varFileName
Dim objFSO
Dim objFile

' Holding variables for user information import from CSV file 
Dim varSamAccountName,varFirstName,varLastName
Dim newUserFields 

Dim objNewUser 
Dim varDomain 

Const ForReading = 1
 
' Modify this name to match your company's AD domain 
varDomain="workdomain.local" 
 
' Create a connection to the Active Directory Users container. 
Set objRootLDAP = GetObject("LDAP://rootDSE") 

' You can give your own OU like LDAP://OU=TestOU instead of LDAP://cn=Users
Set objContainer = GetObject("LDAP://cn=Users," & objRootLDAP.Get("defaultNamingContext")) 

' Specify the csv file full path.
varFileName = "C:\Users\Administrator\Desktop\NewUsers.csv"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(varFileName, ForReading)

' Read the first line - csv columns -not needed for our proceess
objFile.ReadLine

' Skip the error while creating new user...(i.e- user already exists)
on error resume next

' Read the file and create new user.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    newUserFields = Split(objFile.ReadLine,",")
    varSamAccountName = newUserFields(0)
    varFirstName = newUserFields(1) 
    varLastName = newUserFields(2) 
 
' Create new User account 
Set objNewUser = objContainer.Create("User","cn="&varFirstName&" "&varLastName) 
 
objNewUser.put "sAMAccountName",lcase(varSamAccountName) 
objNewUser.put "givenName",varFirstName 
objNewUser.put "sn",varLastName 
objNewUser.put "UserPrincipalName",lcase(varSamAccountName)&"@"&varDomain 
objNewUser.put "DisplayName",varFirstName&" "&varLastName 
objNewUser.put "name",lcase(varSamAccountName) 
objNewUser.put "description","This user was created from csv file using vbscript"
 
objNewUser.SetInfo 
objNewUser.Put "pwdLastSet", 0 

' Enable the user account 
objNewUser.AccountDisabled = FALSE
objNewUser.SetInfo 
Loop

MsgBox("Active Directory users created successfully from CSV file using VBScript.")

WScript.Quit  

Create Bulk AD users from CSV File using VB Script with Dynamic 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: CreateBulkADUsersFromCSV_DynamicFilePath.vbs
3. Change the domain name workdomain.local to your own domain name.

Click to get VBScript as a file  Download CreateBulkADUsersFromCSV_DynamicFilePath.vbs
' CreateBulkADUsersFromCSV_DynamicFilePath.vbs
' Sample VBScript to create a AD Users from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit 
 
' Variables needed for LDAP connection 
Dim objRootLDAP 
Dim objContainer 

' Variables needed for CSV File Information
Dim varFileName
Dim objFSO
Dim objFile

' Holding variables for user information import from CSV file 
Dim varSamAccountName,varFirstName,varLastName
Dim newUserFields 

Dim objNewUser 
Dim varDomain 

Const ForReading = 1
 
' Modify this name to match your company's AD domain 
varDomain="workdomain.in" 
 
' Create a connection to the Active Directory Users container. 
Set objRootLDAP = GetObject("LDAP://rootDSE") 

' You can give your own OU like LDAP://OU=TestOU instead of LDAP://cn=Users
Set objContainer = GetObject("LDAP://cn=Users," & objRootLDAP.Get("defaultNamingContext")) 


' Asks CSV file path from user.
Do
   varFileName = InputBox ("Please enter CSV file full path")
   If varFileName = "" then
      Msgbox "No user name entered"
   end if
Loop Until varFileName <> ""

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(varFileName, ForReading)

' Read the first line - csv columns -not needed for our proceess
objFile.ReadLine

' Skip the error while creating new user...(i.e- user already exists)
on error resume next

' Read the file and create new user.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    newUserFields = Split(objFile.ReadLine,",")
    varSamAccountName = newUserFields(0)
    varFirstName = newUserFields(1) 
    varLastName = newUserFields(2) 

 
' Create new User account 
Set objNewUser = objContainer.Create("User","cn="&varFirstName&" "&varLastName) 
 
objNewUser.put "sAMAccountName",lcase(varSamAccountName) 
objNewUser.put "givenName",varFirstName 
objNewUser.put "sn",varLastName 
objNewUser.put "UserPrincipalName",lcase(varSamAccountName)&"@"&varDomain 
objNewUser.put "DisplayName",varFirstName&" "&varLastName 
objNewUser.put "name",lcase(varSamAccountName) 
objNewUser.put "description","This user was created from csv file using vbscript"
 
objNewUser.SetInfo 
objNewUser.Put "pwdLastSet", 0 

' Enable the user account 
objNewUser.AccountDisabled = FALSE
objNewUser.SetInfo 
Loop

MsgBox("Active Directory users created successfully from CSV file using VBScript.")

WScript.Quit  
4. Double-click the vb script file (or Run this file from command window) to create Bulk Active Directory users from CSV file.

5. Enter the CSV file path which contains new users information to create.

Create Bulk AD users from CSV file

6.
Click OK to proceed. Now Bulk AD Users created successfully from CSV file using VBScript. you can check new users through ADUC console.

Wednesday, 16 October 2013

Create user in Active Directory by VBScript

Description

    This article contains VBScript code to create user in Active Directory with various methods and it also contains  VBScript code to Create Bulk AD users from CSV file.

Related Articles: Create AD User Powershell Script , Powershell Script to Create Bulk AD Users from CSV

Summary

  1. Create Active Directory user by VB Script.
  2. Create Active Directory user in VB Script by user inputs.
  3. Create Bulk AD users using VB Script.
  4. Create Bulk AD users from CSV file using VB Script.

Create Active Directory user by VB Script

1. Copy the below example VB Script code and paste it in notepad or a VBScript editor.
2. Change the value for strUserName if you want to give your own name otherwise simply leave it.
3. Save the file with a .vbs extension, for example: CreateADUser.vbs
4. Double-click the vb script file (or Run this file from command window) to create AD user.

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

Click to get VBScript code as file Download CreateADUser.vbs
' CreateADUser.vbs
' Sample VBScript to create a User in Active Directory .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserName
Dim objRootLDAP
Dim objContainer
Dim objNewUser
strUserName = "MorganTestUser" 

Set objRootLDAP = GetObject("LDAP://rootDSE")

' You can give your own OU like LDAP://OU=TestOU instead of LDAP://CN=Users
Set objContainer = GetObject("LDAP://CN=Users," & _
objRootLDAP.Get("defaultNamingContext")) 

Set objNewUser = objContainer.Create("User", "cn=" & strUserName)
objNewUser.Put "sAMAccountName", strUserName
objNewUser.Put "givenName", "Morgan"
objNewUser.Put "sn", "TestUser"
objNewUser.Put "displayName", "Morgan TestUser"
objNewUser.Put "Description", "AD User created by VB Script"
objNewUser.SetInfo

objNewUser.SetPassword "MyPassword123"
objNewUser.Put "PasswordExpired", CLng(1)
objNewUser.AccountDisabled = FALSE

MsgBox ("New Active Directory User created successfully by using VB Script...")

WScript.Quit  

Create Active Directory user in VB Script by user inputs

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: CreateADUserbyUserInputs.vbs
3. Double-click the VBScript file or Run this file from command window
4. Then give the user name in the opened username text box and click OK to proceed...

Note: You can give your own OU like LDAP://OU=TestOU instead of  LDAP://CN=Users

Click to get VBScript code as file Download CreateADUserByUserInputs.vbs
' CreateADUserWithUserInputs.vbs
' Sample VBScript to create a User in Active Directory by User Inputs.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserName
Dim objRootLDAP
Dim objContainer
Dim objNewUser

Do
   strUserName = InputBox ("Please enter user name")
   If strUserName = "" then
      Msgbox "No user name entered"
   end if
Loop Until strUserName <> ""

MsgBox "Please click OK to continue..."

Set objRootLDAP = GetObject("LDAP://rootDSE")

' You can give your own OU like LDAP://OU=TestOU instead of LDAP://CN=Users
Set objContainer = GetObject("LDAP://CN=Users," & _
objRootLDAP.Get("defaultNamingContext")) 

Set objNewUser = objContainer.Create("User", "cn=" & strUserName)
objNewUser.Put "sAMAccountName", strUserName
objNewUser.Put "Description", "AD User created by VB Script"
objNewUser.SetInfo

objNewUser.SetPassword "MyPassword123"
objNewUser.Put "PasswordExpired", CLng(1)
objNewUser.AccountDisabled = FALSE

MsgBox ("New Active Directory User created successfully by using VB Script...")

WScript.Quit

Create Bulk AD users using VB Script

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: CreateBulkADUsers.vbs
3. You can change the value (For i 0 to 5) to any value like (For i 0 to 100) to create 100 users.
4. Double-click the vb script file (or Run this file from command window) to create Active Directory user.

Click to get VBScript code as file Download CreateBulkADUsers.vbs
' CreateBulkADUsers.vbs
' Sample VBScript to create a Bulk of AD Users.
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strUserName
Dim objRootLDAP
Dim objContainer
Dim objNewUser
Dim i

For i = 0 To 5

strUserName = "MorganTestUser"& i 

Set objRootLDAP = GetObject("LDAP://rootDSE")

' You can give your own OU like LDAP://OU=TestOU instead of LDAP://CN=Users
Set objContainer = GetObject("LDAP://CN=Users," & _
objRootLDAP.Get("defaultNamingContext")) 


Set objNewUser = objContainer.Create("User", "cn=" & strUserName)
objNewUser.Put "sAMAccountName", strUserName
objNewUser.Put "Description", "Bulk AD User created by VB Script"
objNewUser.SetInfo

objNewUser.SetPassword "MyPassword123"
objNewUser.Put "PasswordExpired", CLng(1)
objNewUser.AccountDisabled = FALSE

Next

MsgBox (i &" AD Users created successfully by using VB Script...")

WScript.Quit  

Create Bulk AD users from CSV File using VB Script

1. Copy the below example VB Script code and paste it in notepad or a VBScript editor.
2. Save the file with a .vbs extension, for example: CreateBulkADUsers.vbs
3. Change the CSV file path C:\Users\Administrator\Desktop\NewUsers.csv with your own file path.
4. Change the domain name workdomain.local to your own domain name.

Note:Your CSV file should contain the columns samAccount, givenName and sn as first three columns

Create Bulk Active Directory users from CSV File in VB Script


5. Double-click the vb script file (or Run this file from command window) to create Bulk Active Directory users from CSV file.

Click to get VBScript code as file Download CreateBulkADUsersFromCSVFile.vbs
' CreateBulkADUsersFromCSVFile.vbs
' Sample VBScript to create a AD Users from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit 
 
' Variables needed for LDAP connection 
Dim objRootLDAP 
Dim objContainer 

' Variables needed for CSV File Information
Dim varFileName
Dim objFSO
Dim objFile

' Holding variables for user information import from CSV file 
Dim varSamAccountName,varFirstName,varLastName
Dim newUserFields 

Dim objNewUser 
Dim varDomain 

Const ForReading = 1
 
' Modify this name to match your company's AD domain 
varDomain="workdomain.local" 
 
' Create a connection to the Active Directory Users container. 
Set objRootLDAP = GetObject("LDAP://rootDSE") 

' You can give your own OU like LDAP://OU=TestOU instead of LDAP://cn=Users
Set objContainer = GetObject("LDAP://cn=Users," & objRootLDAP.Get("defaultNamingContext")) 

' Specify the csv file full path.
varFileName = "C:\Users\Administrator\Desktop\NewUsers.csv"

' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(varFileName, ForReading)

' Read the first line - csv columns -not needed for our proceess
objFile.ReadLine

' Skip the error while creating new user...(i.e- user already exists)
on error resume next

' Read the file and create new user.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    newUserFields = Split(objFile.ReadLine,",")
    varSamAccountName = newUserFields(0)
    varFirstName = newUserFields(1) 
    varLastName = newUserFields(2) 

' Create new User account 
Set objNewUser = objContainer.Create("User","cn="&varFirstName&" "&varLastName) 
 
objNewUser.put "sAMAccountName",lcase(varSamAccountName) 
objNewUser.put "givenName",varFirstName 
objNewUser.put "sn",varLastName 
objNewUser.put "UserPrincipalName",lcase(varSamAccountName)&"@"&varDomain 
objNewUser.put "DisplayName",varFirstName&" "&varLastName 
objNewUser.put "name",lcase(varSamAccountName) 
objNewUser.put "description","This user was created from csv file using vbscript"
 
objNewUser.SetInfo 
objNewUser.Put "pwdLastSet", 0 

' Enable the user account 
objNewUser.AccountDisabled = FALSE
objNewUser.SetInfo 
Loop

MsgBox("Active Directory users created successfully from CSV file using VBScript.")

WScript.Quit