Posts RSS Comments RSS 253 Posts and 411 Comments till now

Some AD Functions for DCs and name conversion.

Below are some functions I have written or used recently that I don’t believe I shared before

Get-DC: Gets a DirectoryServices.ActiveDirectory.DomainController object by Name or Domain. If nothing is passed it gets a DC from the current domain

Get-DCConnectionObject: Gets the connection objects for the given DC. Default is all DCs

ConvertTo-Sid: Converts Name to SID.

ConvertTo-Name: Converts Sid to Name.

################################################################################
function Get-DC
{
    Param($Name,$Domain)
   
    if($Name)
    {
        $Context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("DirectoryServer",$Name)
        [System.DirectoryServices.ActiveDirectory.DomainController]::GetDomainController($Context)
    }
    if($Domain)
    {
        $Context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$Domain)
        [System.DirectoryServices.ActiveDirectory.DomainController]::FindAll($Context)
    }
    if(!$Name -and !$Domain)
    {
        $DCName = ([adsi]"LDAP://rootDSE").dnsHostname.ToString()
        $Context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("DirectoryServer",$DCName)
        [System.DirectoryServices.ActiveDirectory.DomainController]::GetDomainController($Context)
    }
}
################################################################################
function Get-DCConnectionObject
{
    Param($name = ".*")
    $Myforest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
    $MyDCs = $Myforest.Domains | foreach-object{$_.DomainControllers} | ?{$_.name -match $name}
    $MyDCs | %{$_.InboundConnections}
}
################################################################################
function ConvertTo-Sid($UserName,$domain = $env:Computername)
{
   $ID = New-Object System.Security.Principal.NTAccount($domain,$UserName)
   $SID = $ID.Translate([System.Security.Principal.SecurityIdentifier])
   $SID.Value
}
################################################################################
function ConvertTo-Name($sid)
{
   $ID = New-Object System.Security.Principal.SecurityIdentifier($sid)
   $User = $ID.Translate( [System.Security.Principal.NTAccount])
   $User.Value
}

Trackback this post | Feed on Comments to this post

Leave a Reply

You must be logged in to post a comment.