List a User's Active Directory Groups with VB.NET

Here's a tool, written in Visual Basic.NET, that lists what groups a user is in. That's right, not Perl this time. I write in other languages, and I realize that not everyone is looking for examples in Perl. So I figure I'll mix it up a bit.

This tool is capable of listing groups across multiple domains, which many tools are not. The project requires adding a reference to the Active DS Type Library. I'm using the NameTranslate interface to to translate name types, which I explain in my previous post. I also use the System.Security.Principal namespace from the .Net framework to get the group list.

Imports System.Security.Principal
Imports ActiveDs
Module Module1
Sub Main()
Dim NAMETYPE_UNKNOWN As Integer = 8
        Dim NAMETYPE_UPN As Integer = 9
        Dim NAMETYPE_NT4 As Integer = 3
        Dim NAMETYPE_SID As Integer = 12
        Dim INITTYPE_GC As Integer = 3
Dim username As String = Microsoft.VisualBasic.Command()
If username = "" Then
            Console.WriteLine("Usage: grouplist domain\username")
            Exit Sub
        End If
Dim nto As New NameTranslate
        nto.Init(INITTYPE_GC, "")
Try
nto.Set(NAMETYPE_UNKNOWN, username)
            Dim upn As String = nto.Get(NAMETYPE_UPN)
            Dim user As WindowsIdentity = New WindowsIdentity(upn)
            Dim groupList As IdentityReferenceCollection
            Dim group As IdentityReference
            groupList = user.Groups
            Dim x As Integer = 0
            For Each group In groupList
                Try
                    nto.Set(NAMETYPE_SID, group.Value)
                    Dim groupName As String = nto.Get(NAMETYPE_NT4)
                    Console.WriteLine(groupName)
                    x += 1
                Catch
                End Try
            Next
            Console.WriteLine(x & " Groups")
Catch ex As Exception
Console.WriteLine("User not Found")
End Try
End Sub
End Module

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...