Sunday, March 8, 2015

C# & PowerShell

This post is to keep a record of what I had done with PowerShell. I have been using PowerShell for quite some time dealing with automation in Active Directory (AD) and System Center Configuration Management (SCCM). I discover that PowerShell can do a lot more thing than I was expected. 

In this post, I will use the example of how to automate in checking a user whether he/she is a member of a particular Active Directory (AD) group. It is written in PowerShell script, but I wanted to explore one more option with C#, knowing the truth that both options will work just fine. The intention is to find out the scripting difference between C# and PowerShell.

Concept

AD has a Directory Service which allow clients to query and manipulate directory objects. There are several methods to access directory service, and the commons are: 
  1. LDAP (Lightweight Directory Access Protocol)
  2. ADSI (Active Directory Service Interface)
In order to check a user whether he/she is a member of a particular AD group, we need to do a query search in AD. The concept is similar to query something from a database. The way how the data is being queried from the database is different from AD. We use SQL to query data from database, but we use LDAP to access directory service to query data from AD.

LDAP is a directory service protocol that run over TCP. Therefore, there are sets of TCP communication between client and directory service to establish session and data exchange. However, we do not need to worry in such low level implementation as we have Directory Service library in .NET Framework.

Implementation

C# version:


Add the Directory Service library reference in to your project.



Create a function for group member search:

public static bool IsGroupMember(string userName, string groupDN)
{
    var searcher = new DirectorySearcher("LDAP://DC=<Your Domain Name>,DC=com");
    searcher.Filter = "(&(objectCategory=person)(CN=" + userName + "))";
    searcher.SearchScope = SearchScope.Subtree;
    searcher.PropertiesToLoad.Add("memberOf");

    var result = searcher.FindAll();

    if (result != null)
    {
        return result[0].Properties["memberOf"].Contains(groupDN);
    }

    return false;
}


The function usage is to pass in the user name that you want to search in the group name.

PowerShell version:

function IsGroupMember($userName, $groupDN)
{
    $searcher = new-object System.DirectoryServices.DirectorySearcher("LDAP://DC=<Your Domain Name>,DC=com")
    $searcher.filter = "(&(objectCategory=person)(CN=$userName))"
    $searcher.SearchScope = "subtree"
    $searcher.PropertiesToLoad.Add("memberOf")

    $result = $searcher.findall()
   
    if ($result -ne $null)
    {
        return $result.Properties.memberof.Contains($groupDN)
    }
}

Hybrid version:


What I like about PowerShell is I can simply invoke any method in C# dll. The benefit of doing so is you can write complex code in C# which you think it is difficult to be written in PowerShell. System engineer will be saved from the horror of coding by just writing simple PowerShell script to call the method in C# which can perform sophisticated execution.

I have created a framework which contains all the functionalities that used to query and manipulate Active Directory related objects and groups, named ADFX. Since this framework was developed in C#, therefore, it can be shared with PowerShell, ASP.NET, windows service, console application, anything which are developed with .NET.

So, instead of having System Engineer to study Directory Service module from .NET Framework, they just need to write a simple PowerShell script below:

Import-Module -Name "C:\Users\Seng-Liang.S.Lee\Desktop\ADFX.dll"

$membership = New-Object ADFX.Membership
$membership.IsGroupMember("<Your User Name>", "<Your Group Distinguished Name>")


Summary

I find that C# and PowerShell are quite the same. Compare the C# code and the PowerScript, both look quite similar. How you write in C#, you can also write the same way in PowerShell, of course except the syntax are different. However, semantically they are the same.

PowerShell is able to import and use with any .NET built component which I like the most. It gives you the flexibility in dividing or separating the complex coding to be done in C# which are Software Engineer expertise, while we leave the easy one to be done in PowerShell which System Engineer can coped with.  



No comments:

Post a Comment

Send Transactional SMS with API

This post cover how to send transactional SMS using the Alibaba Cloud Short Message Service API. Transactional SMS usually come with One Tim...