by

How to Get AD Forest in PowerShell

Here’s another small PowerShell script useful for your administration. It returns the AD object for a specified forest; the forest in the current context is returned  if nothing is passed as parameter. This is also compatible with Office 365.
function Get-Active-Directory-Forest-Object ([string]$ForestName, [System.Management.Automation.PsCredential]$Credential)
{    
    #if forest is not specified, get current context forest
    If (!$ForestName)     
    {        $ForestName = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name.ToString()    
    }        

    If ($Credential)     
    {        
        $credentialUser = $Credential.UserName.ToString()
        $credentialPassword = $Credential.GetNetworkCredential().Password.ToString()
        $adCtx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("forest", $ForestName, $credentialUser, $credentialPassword )
    }    
    Else     
    {        
        $adCtx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("forest", $ForestName)    
    }        

    $output = ([System.DirectoryServices.ActiveDirectory.Forest]::GetForest($adCtx))    

    Return $output
}



By

No comments:

Post a Comment