You can get an Active Directory User’s GUID and SID in C# by using UserPrincipal class. The UserPrincipal class exists under the namespace System.DirectoryServices.AccountManagement and it is available only from .NET 3.5.
# 1 – Create a new Console Application project in Visual Studio.
# 2 – Add a a.NET reference System.DirectoryServices.AccountManagement
# 3 – Then use the below code to get currently logged in user’s Name, GUID, SID and UserPrincipalName.
using System;
using System.DirectoryServices.AccountManagement;
namespace ADUserInfo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Name: " + UserPrincipal.Current.Name);
Console.WriteLine("GUID: " + UserPrincipal.Current.Guid);
Console.WriteLine(" SID: " + UserPrincipal.Current.Sid);
Console.WriteLine("UPN: " + UserPrincipal.Current.UserPrincipalName);
}
}
}
Advertisement
Powershell do not have .Current method.
In Powershell you must before loading the AccountManagement module and then works.
You can load the module with this Code:
$OrgLocation = Get-Location
Set-Location “C:\Windows\Microsoft.Net\assembly”
Set-Location (Get-ChildItem -Path “System.DirectoryServices.AccountManagement.dll” -Recurse).Directory
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
Set-Location $OrgLocation
Remove-Variable OrgLocation
And then you can see with this code that working fine:
Write-Host “Name: “([System.DirectoryServices.AccountManagement.UserPrincipal]::Current.Name)
Write-Host “GUID: “([System.DirectoryServices.AccountManagement.UserPrincipal]::Current.Guid)
Write-Host ” SID: “([System.DirectoryServices.AccountManagement.UserPrincipal]::Current.Sid)
Write-Host “UPN: “([System.DirectoryServices.AccountManagement.UserPrincipal]::Current.UserPrincipalName)