locked
Loading the PowerShell AD Group Details from PSObject into WebGrid. RRS feed

  • Question

  • User-1549556126 posted

    I have explored a lot of resources but there is no information in anywhere about how to utilize the PSObject values that has multiple AD attributes into the webGrid or HTML Table. I have a simple string function that I am using to fetch the details from PowerShell Script. The PS Object has the details returned by the script but I can't figure out a way to bind the webGrid Columns with those attributes. Basically, the object has column name and row values.

    The Script that I am Passing is :

    $GroupName ='Test - Group'
    $SamAccountName = Get-ADGroup -Filter { CN -eq $GroupName } -Properties  SamAccountName | Select -ExpandProperty SamAccountName
    
    #Getting Members of the Group - Not Storing Employee Number
    Get-ADGroupMember -Identity $SamAccountName | where {$_.objectclass -eq 'user'} | 
    Get-ADUser -Properties displayname,  samAccountName, ObjectGUID | 
    Select displayname, samAccountName, ObjectGUID
    public List<string> PowerShellExecutorGrd(string scriptPath, string arg)
            {
                string outString = "";
                var shell = PowerShell.Create();
                shell.Commands.AddCommand(scriptPath).AddArgument(arg);
                var results = shell.Invoke();
                if (results.Count > 0)
                {
                    var builder = new StringBuilder();
                    foreach (var psObj in results)
                    {
                        builder.Append(psObj.ToString().Trim('@').Trim('{').Trim('}') + "\n\r");
                    }
                    outString = Server.HtmlEncode(builder.ToString());
                }
                List<string> strLst = outString.Split(new char[] { '\n' }).ToList();
                shell.Dispose();
                return strLst;
            }

    And the values that strLst stores is :

    displayname=User1; samAccountName=usr1; ObjectGUID=8a3fab53-4c8b-483d-89f0-e26de236a627
    displayname=User2; samAccountName=usr2; ObjectGUID=0a3fab53-4c8b-483d-89f0-e26de236a627
    displayname=User3; samAccountName=usr3; ObjectGUID=9a3fab53-4c8b-483d-89f0-e26de236a627

    I am using JsonResult method to migrate value from controller to my View:

    [HttpPost]
            public JsonResult FillMembers(string GroupName)
            {
                var SDC = PowerShellExecutorGrd(AppDomain.CurrentDomain.BaseDirectory + "Shell\\Get-ADGroupMembers.ps1", GroupName);
                return Json(new { message = SDC }, JsonRequestBehavior.AllowGet);
            }

    On my View I am invoking the function on ajax using script block:

     $.ajax({
                            type: "POST",
                            url: "/Group/FillMembers",
                            data: { GroupName: $("#ddlGroup option:selected").text().trim() },
                            success: function (response) {
                                $("#txtMembers").val(response.message);
                            }
                        });

    The output I am trying to have is as follows:

    displayName samAccountName ObjectGUID
    User1 Usr1 8a3fab53-4c8b-483d-89f0-e26de236a627
    User2 Usr2 0a3fab53-4c8b-483d-89f0-e26de236a627
    User3 Usr3 9a3fab53-4c8b-483d-89f0-e26de236a627

    How do I load this data into a webGrid with the property as column name & values as the data? I used HTML Razor Syntax to design GUI.

    Monday, June 10, 2019 6:48 PM

Answers

  • User1724605321 posted

    Hi vyasnikul ,

    Since you are returning the List<string> to client side , you can try below code sample :

    <div id="tbl">
        <table>
            <thead>
                <tr id="thead">
                    <th>displayName</th>
                    <th>samAccountName</th>
                    <th>ObjectGUID</th>
                </tr>
            </thead>
            <tbody id="tbody">
            </tbody>
        </table>
    </div>

    JS :

        $(function(){
            
            $.ajax({
                type: "POST",
                url: "/Group/FillMembers",           
                success: function (response) {
                    $.each(response.message, function (key, value) {
                        var arr = value.split(";")
                        var tbody = $("#tbody");
                        var tr = $("<tr></tr>")
                        $.each(arr, function (i, obj) {
                            var temp = arr[i].trim().split("=")[1];
                            var td = $("<td></td>")
                            td.append(temp);
                            tr.append(td);
                        })
                        tbody.append(tr);
    
                    });            
                }
            });      
        })

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 11, 2019 2:51 AM
  • User753101303 posted

    Here is a quick Console demo that shows how you could query an AD group with this namespace :

    using System;
    using System.DirectoryServices.AccountManagement;
    namespace ConsoleDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                const string groupName = @"Domain\TheGroupName";
                using (var context = new PrincipalContext(ContextType.Domain))
                {
                    using (var grp = GroupPrincipal.FindByIdentity(context, groupName))
                    {
                        foreach (var member in grp.GetMembers())
                        {
                            Console.WriteLine("{0}, {1}, {2}", member.DisplayName, member.SamAccountName, member.Guid);
                        }
                    }
                }
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 12, 2019 6:10 PM

All replies

  • User1724605321 posted

    Hi vyasnikul ,

    Since you are returning the List<string> to client side , you can try below code sample :

    <div id="tbl">
        <table>
            <thead>
                <tr id="thead">
                    <th>displayName</th>
                    <th>samAccountName</th>
                    <th>ObjectGUID</th>
                </tr>
            </thead>
            <tbody id="tbody">
            </tbody>
        </table>
    </div>

    JS :

        $(function(){
            
            $.ajax({
                type: "POST",
                url: "/Group/FillMembers",           
                success: function (response) {
                    $.each(response.message, function (key, value) {
                        var arr = value.split(";")
                        var tbody = $("#tbody");
                        var tr = $("<tr></tr>")
                        $.each(arr, function (i, obj) {
                            var temp = arr[i].trim().split("=")[1];
                            var td = $("<td></td>")
                            td.append(temp);
                            tr.append(td);
                        })
                        tbody.append(tr);
    
                    });            
                }
            });      
        })

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 11, 2019 2:51 AM
  • User753101303 posted

    Hi,

    For now you return a string for each user. Though parsing strings works, my approach would be to take each value to populate a real class and handle that this way with multiple properties. BTW given how PowerShell works I believe you might be able to get an object back rather than just a string output. Is this the direction you want to ttake ?

    It would allow to swap using PowerShell with something else later (or now ?). If using a recent version, I believe it would be easier to query AD using https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.groupprincipal?view=netframework-4.8 (using FindByIdentity to get the group and GetMembers to get group members)

    Tuesday, June 11, 2019 7:19 AM
  • User-1549556126 posted

    Patrice,

    This is new to me but I'll take a look at it for sure. Meanwhile, if you have any sources where they provide examples please let me know.

    Thank you so much for this idea.

    Tuesday, June 11, 2019 3:42 PM
  • User-1549556126 posted

    Perfectly, working Nan Thanks. PowerShell is amazing to work on but a bit challenging when we need to deal with creating a GUI to perform operations.

    Tuesday, June 11, 2019 4:50 PM
  • User753101303 posted

    Here is a quick Console demo that shows how you could query an AD group with this namespace :

    using System;
    using System.DirectoryServices.AccountManagement;
    namespace ConsoleDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                const string groupName = @"Domain\TheGroupName";
                using (var context = new PrincipalContext(ContextType.Domain))
                {
                    using (var grp = GroupPrincipal.FindByIdentity(context, groupName))
                    {
                        foreach (var member in grp.GetMembers())
                        {
                            Console.WriteLine("{0}, {1}, {2}", member.DisplayName, member.SamAccountName, member.Guid);
                        }
                    }
                }
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 12, 2019 6:10 PM