Wednesday, 16 April 2014

VBScript to Get AD Group Members

Description:

In this article, I am going to write vbscript code to find and get list of group members in Active Directory domain. it contains vbscript samples to get list of Active Directory Group member names in command line output and vbscript to export AD Group members into CSV file.

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

Summary:

Get list of AD Group Members in command line output 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: GetADGroupMembers.vbs
3. Run usage in CMD:
C:\> CScript <vbscript file path> <groupName>
Example: CScript C:\Scripts\GetADGroupMembers.vbs "Domain Admins"

4. Run the above command to get Active Directory members list

Click to get vbscript code as file Download GetADGroupMembers.vbs

' GetADGroupMembers.vbs
' Sample VBScript to Get List of AD Group Members.
' CMD Usage: 
'     CScript <vbscript file path> <groupName>
' Ex: CScript C:\Scripts\GetADGroupMembers.vbs "Domain Admins"
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Dim groupName,strMember
Dim objGroup,objMember

if Wscript.arguments.count = 0 then
    Wscript.echo "Invalid input parameters"
    Wscript.echo "   "
    Wscript.echo "Script Usage:"
    Wscript.echo "----------------------------------------"
    Wscript.echo "CScript <vbscript file path> <groupName>"
    Wscript.echo "---------------------------------------"
    Wscript.echo "Ex: CScript C:\Scripts\GetADGroupMembers.vbs ""Domain Admins"" "
    Wscript.echo "---------------------------------------"
    WScript.quit
else
 
  ' Get the group name from command line parameter
    groupName = WScript.Arguments(0)

end if

' Get the distinguished name of the group
Set objGroup = GetObject("LDAP://" & GetDN(groupName))

' List the member’s full name in the group
For Each strMember in objGroup.Member
    Set objMember =  GetObject("LDAP://" & strMember)
    Wscript.Echo objMember.CN
Next

WScript.quit
' Active Directory Group Members listed successfully using VBScript

'****************Function to Get DN of group****************
' 
Function GetDN(groupName)

Dim objRootDSE, adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim adoRecordset

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

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

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

' Filter on group objects.
varFilter = "(&(objectClass=group)(|(cn="& groupName &")(name="& groupName &")))"

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

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

' Run the query.
Set adoRecordset = adoCommand.Execute

IF(adoRecordset.EOF<>True) Then
   GetDN=adoRecordset.Fields("distinguishedname").value
Else 
   'No group found 
End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

End Function

'****************End of Function to Get DN of group****************

AD Group members command line output:

VBScript to Get Active Directory Group Members

VBScript to Export AD Group Members into CSV file

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: ExportADGroupMembers.vbs
3. Run usage in CMD:
C:\> CScript <vbscript filepath> <groupName> <csvFilePath>
Example: CScript ExportADGroupMembers.vbs "Domain Admins" "C:\ADGroupMembers.csv"

4. Run the above command to Export Active Directory members into CSV file

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

' ExportADGroupMembers.vbs
' Sample VBScript to Export AD Group Members into CSV file.
' CMD Usage: CScript <vbscript filepath> <groupName> <csvFilePath>
' Ex: CScript ExportADGroupMembers.vbs "Domain Admins" "C:\ADGroupMembers.csv"
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Dim groupName,strMember,csvFilePath
Dim objGroup,objMember
Dim objFSO, objCSVFile

if Wscript.arguments.count < 2 then
    Wscript.echo "Invalid input parameters"
    Wscript.echo "   "
    Wscript.echo "Script Usage:"
    Wscript.echo "-----------------------------"
    Wscript.echo "CScript <vbscript file path> <groupName> <csvFilePath>"
    Wscript.echo "   "
    Wscript.echo "Ex: CScript C:\Scripts\ExportADGroupMembers.vbs ""Domain Admins"" "&_
                      " ""C:\ADGroupMembers.csv"" "
    WScript.quit
else
 
  ' Get the group name and csv file path from command line parameters
    groupName = WScript.Arguments(0)
    csvFilePath = WScript.Arguments(1)

end if

' Get the distinguished name of the group
Set objGroup = GetObject("LDAP://" & GetDN(groupName))

' Create CSV file 
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

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

' Write AD Attributes CN and distinguishedname 
' as CSV columns(first line)

 objCSVFile.Write "CN,distinguishedname"

 objCSVFile.Writeline ' New Line


' List the member’s full name in the group
For Each strMember in objGroup.Member
    Set objMember =  GetObject("LDAP://" & strMember)
   ' Retrieve values and write into CSV file.

     objCSVFile.Write objMember.CN & "," 
     objCSVFile.Write """" &strMember & """" 
     objCSVFile.Writeline  ' New Line
Next

Wscript.echo "AD Group '"&groupName&"' members are Exported into CSV file '"&_
             csvFilePath&"'"

WScript.quit
' Active Directory Group Members listed successfully using VBScript

'****************Function to Get DN of group****************
' 
Function GetDN(groupName)

Dim objRootDSE, adoCommand, adoConnection
Dim varBaseDN, varFilter, varAttributes
Dim adoRecordset

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

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

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

' Filter on group objects.
varFilter = "(&(objectClass=group)(|(cn="& groupName &")(name="& groupName &")))"

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

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

' Run the query.
Set adoRecordset = adoCommand.Execute

IF(adoRecordset.EOF<>True) Then
   GetDN=adoRecordset.Fields("distinguishedname").value
Else 
   'No group found 
End if

' close ado connections.
adoRecordset.Close
adoConnection.Close

End Function

'****************End of Function to Get DN of group****************

Export Active Directory Group members CMD usage:

VBScript to Export Active Directory Group Members into CSV file

 AD Group members CSV file output:

Export Active Directory Group Members into CSV file using VBScript


Thanks,
Morgan
Software Developer

Set Session value in JavaScript

Description:

In this article, I am going write examples to access and set Session variable Value in JavaScript and how to Set Session variable value from JavaScript in ASP.NET using PageMethods, XMLHttpRequest and JQuery Ajax call.

Summary:


Set Session value in JavaScript using PageMethods

You can get and set session variable value from JavaScript in ASP.NET using Ajax ScriptManager's PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods="True".

Check the below example to set and get session value in JavaScript using PageMethods.

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

    [System.Web.Services.WebMethod]
    public static void SetSessionValue(string key,string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        if (HttpContext.Current.Session[key] != null)
        {
            return HttpContext.Current.Session[key].ToString();
        }
        else
        {
            return "Session value not found";
        }
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session Value from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">

        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;
            PageMethods.SetSessionValue('UserName', userName, null, null);
        }

        function GetUserName() {
            PageMethods.GetSessionValue('UserName', OnSuccess, OnFailure);
        }
        function OnSuccess(userName) {
            document.getElementById("lbUserName").innerHTML = userName;
        }
        function OnFailure(error) {
            alert(error);
        }
  
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Set Session value in JavaScript using XMLHttpRequest in ASP.NET

You can set and get server side session variable value from JavaScript in ASP.NET using using XMLHttpRequest. The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can access Server Side value from JavaScript client side by using this object without refreshing or reloading the page.

Check the below example to get and set session value in JavaScript in ASP.NET using XMLHttpRequest.

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Method"] == "SetUserName")
        {
            SetUserName(Request.QueryString["Value"].ToString());
        }
        else if (Request.QueryString["Method"] == "GetUserName")
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            GetUserName();
        }
    }

    private void SetUserName(string userName)
    {
        Session["UserName"] = userName;
    }

    private void GetUserName()
    {
        Response.Clear();
        if (Session["UserName"] != null)
        {
            Response.Write(Session["UserName"].ToString());
        }
        else
        {
            Response.Write("Session Value not found");
        }
        Response.End();
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set Session variable value in JavaScript using XMLHttpRequest</title>
    <script type="text/javascript">
        function SetUserName() {
            var userName = document.getElementById("tbUserName").value;            
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "WebForm1.aspx?Method=SetUserName&Value=" + userName;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);                     
        }

        function GetUserName() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "WebForm1.aspx?Method=GetUserName";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("lbUserName").innerHTML = xmlhttp.responseText;
        }
 
    </script>
     
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>

Get and Set Session value in JavaScript using JQuery ajax call

You can access or set session variable value from JavaScript in ASP.NET using using JQuery ajax method.

Check the below example to set 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)
    {
    }

    [System.Web.Services.WebMethod]
    public static void SetSessionValue(string key, string value)
    {
        HttpContext.Current.Session[key] = value;
    }

    [System.Web.Services.WebMethod]
    public static string GetSessionValue(string key)
    {
        if (HttpContext.Current.Session[key] != null)
        {
            return HttpContext.Current.Session[key].ToString();
        }
        else
        {
            return "Session value not found";
        }
    }
Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Set 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 SetUserName() {
            var userName = document.getElementById("tbUserName").value;
            $.ajax({
                type: "post",
                url: "WebForm3.aspx/SetSessionValue",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"key":"UserName","value":"' + userName + '"}',
                success: function (result) {
                    //Session value saved successfully
                },
                error: function (xhr, status, error) {
                    //Failed to save Session value
                }
            });
        }

        function GetUserName() {
            $.ajax({
                type: "post",
                url: "WebForm3.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>
        Enter an user name,
        <input id="tbUserName" type="text" />
<input type="button" value="Set User Name" onclick="SetUserName()" /><br />
        <input type="button" value="Show UserName" onclick="GetUserName()" />
    <label id="lbUserName">This is a username from session variable</label>
    </div>
    </form>
</body>
</html>



Thanks,
Morgan
Software Developer