Thursday, 26 February 2015

Get Session value in JavaScript using JQuery ajax

In this article, I am going write C# and JavaScript code sample to access or check session value in JavaScript in ASP.NET using JQuery Ajax call.

Check Session value in JavaScript using JQuery ajax call:

You can access or get session variable value from JavaScript in ASP.NET using using JQuery ajax method. Check the below example to get session variable value in JavaScript using JQuery ajax call.

Note: You need add reference for JQuery script file to use JQuery ajax method.

Default.aspx.cs:
  protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserName"] = "Administrator";
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        return HttpContext.Current.Session[key].ToString();
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Get Session value from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function GetLoginUser() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        function OnFailure(error) {
            alert(error);
        }
  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show User Name" onclick="GetLoginUser()" />
        <label id="lbUserName">
            This is currently logged in user name</label>
    </div>
    </form>
</body>
</html>
Read More...

Wednesday, 25 February 2015

Call Server Side method from JavaScript using PageMethods in ASP.NET

In this article, I am going to write C# and JavaScript code sample to Call Server Side method from JavaScript Client Side code using PageMethods in ASP.NET.

Call Server Side method from JavaScript using PageMethods:

You can call server side method from JavaScript using Ajax ScriptManager's PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods="True". Here, I have written an example to get web server time using PageMethods with Ajax call.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">
        function GetServerDate(format) {
            PageMethods.GetServerDate(format, OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
   {
   }

   [System.Web.Services.WebMethod]
   public static string GetServerDate(string format)
   {
       if (format.Equals("utc"))
       {
           return DateTime.Now.ToUniversalTime().ToString();
       }
       else
       {
           return DateTime.Now.ToLocalTime().ToString();
       }
   }
Read More...

Tuesday, 24 February 2015

What is Windows.edb file in windows search

What is Windows.edb?

The Windows.edb is a database file of the indexing service. If you have enabled Windows Indexing or Windows Search feature, this file can become quite large.

Is it safe to delete Windows.edb file?

Yes, it is perfectly safe to delete Windows.edb file. But when you try to delete Windows.edb file without disabling the Windows Search service, you’ll get the error "the action cannot be completed because the file is open in windows search". You first need to disable the Windows Indexing service and then you can delete the Windows.edb file.

How to delete Windows.edb and rebuild index search?

1) Open Service Manager console (or run "services.msc"), search and find the service "Windows Search". Stop the service.
2) Delete the Windows.edb file.
3) Click Start > Search for "Indexing Options" and Open it.
4) Click "Advanced" button and then click "Rebuild" for delete and rebuild index. You can also specify a different drive to store the index on.
Read More...

Call Server side method from JavaScript using JQuery ajax in ASP.NET

In this article, I am going to write C# and JavaScript code examples to Call Server Side method from JavaScript Client Side code in ASP.NET using JQuery ajax,

Summary:

Call Server Side method from JavaScript in ASP.NET using JQuery ajax

   You can call server side C# method from JavaScript client side using JQuery ajax method in ASP.NET.
Note: You need add reference for JQuery script file to use JQuery ajax.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function GetServerDate() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show Server Time" onclick="GetServerDate()" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate()
    {
        return DateTime.Now.ToLocalTime().ToString();
    }



Call Server Side method from JavaScript using JQuery ajax with Parameters

   You can call server side C# method from JavaScript in ASP.NET using JQuery ajax method. Here, I have written JQuery ajax example to get current date time by passing parameters.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function GetServerDate(format) {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"format":"' + format + '"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate(string format)
    {
        if (format.Equals("utc"))
        {
            return DateTime.Now.ToUniversalTime().ToString();
        }
        else
        {
            return DateTime.Now.ToLocalTime().ToString();
        }
    }


Related Articles:

Read More...

VBScript - Export Locked-Out AD Users to CSV file

In this article, I am going write vbscript code to find locked-out AD users and export currently locked-out AD users to CSV file. Here, we are using two attributes LockoutTime and msDS-User-Account-Control-Computed to find currently locked-out users.

Follow the below steps to export Locked-Out AD Users to CSV 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 .
' ------------------------------------------------------' 
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, retrieve values and write into CSV file.
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
     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
Exported CSV File Output of Locked-Out AD Users:

VBScript to Find Locked Out AD Users
Read More...

Active Directory : adminCount attribute and AdminSDHolder

The Active Directory attribute adminCount is used to indicate the protection status of an object. The value of this attribute is set by the system when an object is added to an administrative group/protected group.

Does setting Admincount to 0 revokes protected status of users who are member of protected AD group ?

No, Admincount will automatically revert as 1 by AdminSDHolder (if you edit manually ). By default the process called SDPROP (Security Descriptor Propagation ) is automatically activated every 60 minutes on the PDC emulator of the Active Directory domain and update adminCount value of every security objects by AdminSDHolder code.

What is AdminSDHolder

Active Directory domain has an object called AdminSDHolder, which resides in the System container in the domain (CN=AdminSDHolder,CN=System,DN=domain,DN=com). The AdminSDHolder object has a unique Access Control List (ACL), which is used to control the permissions of security principals that are members of built-in or granted administrative accounts. The AdminCount attribute value will be changed from NULL to 1 when an account granted administrative permissions. The AdminCount attribute on that user account does not change when administrative permission accounts is disabled or revoked, the value 1 remains.

The following Active Directory Powershell cmdlet command detect which users and groups are affected by Protected Group status.

List AD Protected Users:
Import-Module ActiveDirectory
Get-ADUser -LDAPFilter "(admincount=1)" | Select Name,DistinguishedName
List AD Protected Groups:
Import-Module ActiveDirectory
Get-ADGroup -LDAPFilter "(admincount=1)" | Select Name,DistinguishedName
Default protected administrative groups in Active Directory:
  • Enterprise Admins
  • Schema Admins
  • Domain Admins
  • Administrators
  • Account Operators
  • Server Operators
  • Print Operators
  • Backup Operators
  • Cert Publishers
  • Domain Controllers
  • Read-Only Domain Controllers
  • Replicator
Read More...

Saturday, 21 February 2015

VBScript - Create Active Directory Group

This article contains VBScript code to create group in Active Directory and it also contains  VBScript code to Create Bulk AD Groups from CSV file.

Summary

Create Active Directory Group 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 strgroupName if you want to give your own name for new group otherwise simply leave it.
3. Save the file with a .vbs extension, for example: CreateADGroup.vbs
4. Double-click the vb script file (or Run this file from command window) to create AD group.
    Note: You should run this VBScript on a machine with windows Active Directory domain.

Click to get VBScript code as file Download CreateADGroup.vbs
' CreateADGroup.vbs
' Sample VBScript to create a group in Active Directory .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit
Dim strGroupName
Dim objRootLDAP,objContainer,objNewGroup
strGroupName = "MyTestGroup" 

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 objNewGroup = objContainer.Create("Group", "cn=" & strGroupName)
objNewGroup.Put "sAMAccountName", strGroupName
objNewGroup.Put "Description", "AD Group created by VB Script"
objNewGroup.SetInfo

WScript.Echo "New Active Directory Group created successfully by using VB Script..."
WScript.Quit  

Create Bulk AD Groups 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: CreateBulkADGroupsFromCSVFile.vbs
3. Change the CSV file path C:\NewGroups.csv with your own file path.
4. Change the domain name workdomain.local to your own domain name.
    Note:Your CSV file should contain group name as first column
5. Double-click vb script file (or Run this file from command window) to create Bulk Active Directory Groups from CSV file.

Click to get VBScript code as file Download CreateBulkADGroupsFromCSVFile.vbs
' CreateBulkADGroupsFromCSVFile.vbs
' Sample VBScript to create multiple AD Groups from CSV file .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 
Option Explicit  
' Variables needed for LDAP connection 
Dim objRootLDAP,objContainer 
' Variables needed for CSV File Information
Dim varFileName, objFSO, objFile
' Holding variables for group information import from CSV file 
Dim varGroupName, newGroupFields
Dim objNewGroup

Const ForReading = 1  
' 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:\Newgroups.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 group...(i.e- group already exists)
on error resume next
' Read the file and create new group.
Do Until objFile.AtEndOfStream
    ' Splits prioperty values.
    newGroupFields = Split(objFile.ReadLine,",")
   'First field as group name
    varGroupName = newGroupFields(0)

' Create new group
Set objNewGroup = objContainer.Create("Group","cn="&varGroupName)  
objNewGroup.put "sAMAccountName",lcase(varGroupName) 
objNewGroup.put "description","This group was created from csv file using vbscript"
objNewGroup.SetInfo 
Loop

WScript.Echo "Active Directory Groups created successfully from CSV file using VBScript."
WScript.Quit  
Read More...

Powershell - Find Protected AD Groups and Users

Protected Groups and Members

You might have faced permission denied (The user has insufficient access rights) problem when modifying a user object, reset password and using Send as permissions in Exchange servers. When permissions are delegated to non-admin users, these permissions rely on the user object that inherits the permissions from the parent container. Members of protected groups do not inherit permissions from the parent container, therefore, these permissions are not applied to members of protected groups. So even though permissions are assigned higher up in the tree, they may not be implemented on users or objects that are members of built-in groups/protected groups.

The Active Directory attribute adminCount indicates whether group is a Protected Group or user is a Protected group Member.

The following Active Directory Powershell cmdlet command detect which users and groups are affected by Protected Group status.

List AD Protected Users:
Import-Module ActiveDirectory
Get-ADUser -LDAPFilter "(admincount=1)" | Select Name,DistinguishedName
List AD Protected Groups:
Import-Module ActiveDirectory
Get-ADGroup -LDAPFilter "(admincount=1)" | Select Name,DistinguishedName
Export AD Protected Users to CSV:
Import-Module ActiveDirectory
Get-ADUser -LDAPFilter "(admincount=1)" |
   Select Name,DistinguishedName |
   Export-CSV "C:\\ProtectedADUsers.csv" -NoTypeInformation -Encoding UTF8
Default protected administrative groups in Active Directory:
  • Enterprise Admins
  • Schema Admins
  • Domain Admins
  • Administrators
  • Account Operators
  • Server Operators
  • Print Operators
  • Backup Operators
  • Cert Publishers
  • Domain Controllers
  • Read-Only Domain Controllers
  • Replicator
Read More...

Thursday, 19 February 2015

AD user not inheriting permissions of non admin user

Problem:

Today, I have faced access denied (The user has insufficient access rights) problem when modifying a user object by using credentials of a non admin user. By default, non-admin users won't have the privilege to modify Active Directory object, I have delegated modify permissions for the non-admin user in one OU so that non-admin users can modify user objects who are under that particular OU. The modify privilege was worked well for some users but not working for some of users. After I have analyzed some time found the reason for this permission inheritance problem is the delegated privilege for the non-admin user is not inherited to the users who are under the group "Domain Admins".

Cause:

When permissions are delegated to non-admin users, these permissions rely on the user object that inherits the permissions from the parent container. Members of protected groups do not inherit permissions from the parent container; therefore, these permissions are not applied to members of protected groups. So even though permissions are assigned higher up in the tree, they may not be implemented on users or objects that are members of built-in groups.

Protected administrative groups in Active Directory:
  • Enterprise Admins
  • Schema Admins
  • Domain Admins
  • Administrators
  • Account Operators
  • Server Operators
  • Print Operators
  • Backup Operators
  • Cert Publishers
  • Domain Controllers
  • Read-Only Domain Controllers
  • Replicator

Solution:

If you have a need to delegate permissions to a non-admin user or group to administer users in an OU, and in that OU reside other protected users. To grant permissions to protected group members, you have to delegate the permissions to an existing admin-type person who are member of protected group or you need to add the non-admin user into the protected group.

For more information about this permission inheritance issue please refer the following Microsoft articles:

Five common questions about AdminSdHolder and SDProp: http://blogs.technet.com/b/askds/archive/2009/05/07/five-common-questions-about-adminsdholder-and-sdprop.aspx

Article 306398 - AdminSDHolder Object Affects Delegation of Control for Past Administrator Accounts: http://support.microsoft.com/default.aspx?scid=kb;en-us;306398

Article 232199 - Description and Update of the Active Directory AdminSDHolder Object: http://support.microsoft.com/?kbid=232199

Article 817433 - Delegated permissions are not available and inheritance is automatically disabled: http://support.microsoft.com/default.aspx?scid=kb;en-us;817433
Read More...

Get Computer Name from IP Address and vise versa in CMD

We can get computer name/machine name from ip address using either ping command or tracert and we can get ip address from computer name using ping command and nslookup command.

Get Computer Name from IP Address in Command Prompt

You can get machine name from ip address using ping command by passing the argument -a.
ping -a 212.168.1.52
You can also convert ip address to computer name using tracert command
tracert 212.168.1.52
Get Computer Name from IP Address and vise versa in CMD

Get IP Address from Computer Name in Command Window

You can get ip address of a computer name by using ping command or nslookup command
nslookup  your-pc-name
-or-
ping -your-pc-name
Read More...

Thursday, 12 February 2015

VBScript - Find Locked-Out AD User Accounts

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

Summary:

Find Currently Locked-Out AD Users using VBScript

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.
Click to get vbscript source code as a file: Download FindLockedoutADUsers.vbs
' FindLockedoutADUsers.vbs
' Sample VBScript to Find Locked-Out Active Directory users.
' 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...
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


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 .
' ------------------------------------------------------' 
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, retrieve values and write into CSV file.
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
     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
Exported CSV File Output of Locked-Out AD Users:

VBScript to Find Locked Out AD Users
Read More...

Wednesday, 11 February 2015

Powershell - Export Disabled AD Users to CSV

We can Find and Export disabled AD Users using Powershell cmdlets Search-ADAccount and Export-CSV. In this article, I am going to write Powershell script samples to Find all disabld AD Users and Export disabled AD Users to CSV file.

Powershell command to find all disabled AD Users:
Search-ADAccount –AccountDisabled -UsersOnly
Search-ADAccount cmdlet lists both users and computers, we need to pass the parameter -UsersOnly to list only users.

Find and List all disabled AD Users

The following command find the disbled ad users by passing the parameter AccountDisabled into Powershell cmdlet Search-ADAccount and list the selected properties of all disabled Active Directory users.
Import-Module ActiveDirectory
Search-ADAccount –AccountDisabled -UsersOnly |
 Select -Property Name,DistinguishedName

Find Disabled AD Users from specific OU:

We can set target OU scope by using the parameter SearchBase in Search-ADAccount cmdlet. This following command select and list all disabled Active Directory users from the Organization Unit 'TestOU'.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –AccountDisabled -UsersOnly |
 Select -Property Name,DistinguishedName

Export Disabled AD Users to CSV using Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all disabled Active Directory users to CSV file.
Import-Module ActiveDirectory
Search-ADAccount –AccountDisabled -UsersOnly |
 Select -Property Name,DistinguishedName |
 Export-CSV "C:\\DisabledADUsers.csv" -NoTypeInformation -Encoding UTF8
Find Disabled Active Directory Users using Powershell

CSV Output of Disabled AD User Accounts:

Find Disabled AD Users using Powershell
Read More...

Wednesday, 4 February 2015

PowerShell: How to Import Active Directory module

If you are going to run Active Directory cmdlets in Powershell. You need to import Active Directory module before executing any cmdlet commands that exists in Active Directory powershell module.

Import Active Directory module:
Import-Module ActiveDirectory
Before start, ensure that the Active Directory module is installed or not by using following command. It will be installed by default in Domain Controller with the AD DS or AD LDS server roles. In client machine or member server (Windows 7 / 2008 R2 server), you need to install it through Remote Server Administration Tools.
Get-Module -Listavailable
How to Import Active Directory module in PowerShell

Install Active Directory module for Powershell:

If the Active Directory module is not installed already, follow the below steps to install.

- Download "Remote Server Administration Tools" from http://www.microsoft.com/download/en/details.aspx?id=7887 and install it
- Go to Windows Add/Remove Feature and enable Active Directory Module for Windows PowerShell. (Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools > Active Directory Module for Windows PowerShell).

How to Install Active Directory module for PowerShell

Once you installed the Active Directory module for Powershell, you can run any cmdlet that exists in Active Directory Powershell module.
Import-Module ActiveDirectory
Get-ADUser -Identity "Morgan"

How to Import Active Directory module in PowerShell

If you are newbie to powershell, don’t forget to set your execution policy to unrestricted or you might get an error when you try run the script. Use the below command to set your execution policy:

Set-ExecutionPolicy Unrestricted
How to Import Active Directory module in PowerShell
Read More...

Tuesday, 3 February 2015

Powershell: Export Locked-Out AD Users to CSV

We can Find and Export Lockout-Out AD Users using Powershell cmdlets Search-ADAccount and Export-CSV. In this article, I am going to write Powershell script samples to Find all Locked-Out AD Users and Export Locked-Out AD Users to CSV file.

Powershell command to find all Locked-Out AD Users:
Search-ADAccount –LockedOut

Find and List All Locked-Out AD Users

The following command find the locked-out ad users by passing the parameter LockedOut into Powershell cmdlet Search-ADAccount and list the selected properties of all locked-out Active Directory users.
Import-Module ActiveDirectory
Search-ADAccount –LockedOut |
 Select -Property Name,DistinguishedName

Find Locked-Out AD Users from specific OU:

We can set target OU scope by using the parameter SearchBase in Search-ADAccount cmdlet. This following command select and list all the Locked-Out Active Directory users from the Organization Unit 'TestOU'.
Import-Module ActiveDirectory
Search-ADAccount  -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –LockedOut |
 Select -Property Name,DistinguishedName

Export Locked-Out AD Users to CSV using Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all locked-out Active Directory users to CSV file.
Import-Module ActiveDirectory
Search-ADAccount –LockedOut |
 Select -Property Name,DistinguishedName |
 Export-CSV "C:\\LockedOutADUsers.csv" -NoTypeInformation -Encoding UTF8
Find and Export Locked-Out AD Users using Powershell
CSV Output of Locked-Out AD User Accounts:

Find and Export Locked-Out AD Users using Powershell
Read More...

Sunday, 1 February 2015

Powershell - Find Inactive AD User Accounts

We can Find and List Inactive AD users using Powershell cmdlet Search-ADAccount with the AccountInactive parameter. In this article, I am going to write Powershell script samples to list all AD Users who are inactive for particular days, Find AD Users who are inactive from particular date and Export Inactive AD Users to CSV file.

Powershell command to list inactive AD Users by TimeSpan:
Search-ADAccount –AccountInactive -TimeSpan "Days.Hrs:Mins:Secs" -UsersOnly
Search-ADAccount  lists both users and computers, we need to pass the parameter -UsersOnly to list only users.

Powershell command to list inactive AD Users by DateTime:
Search-ADAccount –AccountInactive -DateTime "1/10/2015" -UsersOnly

Summary:

Find Inactive AD Users by TimeSpan

The following command find AD users who are not logged in last 90 days by passing the parameters AccountInactive and TimeSpan into Powershell cmdlet Search-ADAccount and list the selected properties of all inactive Active Directory users.
Import-Module ActiveDirectory
Search-ADAccount –AccountInactive -TimeSpan 90.00:00:00 -UsersOnly |
 Select -Property Name,DistinguishedName,LastLogonDate
Find Inactive AD Users with Powershell

Find and List Inactive AD Users by DateTime

The following script find AD users who have not logged in since "1/8/2015" and list the selected properties of all inactive Active Directory users.
Import-Module ActiveDirectory
Search-ADAccount –AccountInactive -DateTime "1/8/2015" -UsersOnly |
 Select -Property Name,DistinguishedName,LastLogonDate

Find Inactive AD Users from specific OU with Powershell

We can set target OU scope by using the parameter SearchBase in Search-ADAccount cmdlet. This following command select and list all the AD users who are not logged in last 90 days from the Organization Unit 'TestOU'.
Import-Module ActiveDirectory
Search-ADAccount -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" –AccountInactive -TimeSpan 90.00:00:00 -UsersOnly |
 Select -Property Name,DistinguishedName,LastLogonDate

Export Inactive AD Users to CSV with Powershell

We can export powershell output into CSV file using Export-CSV cmdlet. The following command export selected properties of all inactive Active Directory users to CSV file.
Import-Module ActiveDirectory
Search-ADAccount –AccountInactive -TimeSpan 90.00:00:00 -UsersOnly |
 Select -Property Name,DistinguishedName,LastLogonDate |
 Export-CSV "C:\\InactiveADUsers.csv" -NoTypeInformation -Encoding UTF8
Find Inactive AD Users with Powershell

CSV Output of Disabled AD User Accounts:

Find and Export Inactive AD Users to CSV with Powershell
Read More...