How to Create Forest Trust Using PowerShell

How to Create Forest Trust Using PowerShell


Recently I got request to create forest transitive trust (with forest-wide authentication) using script. My first steps aimed at NETDOM utility, but after some unsuccessful test I found this:
Important
Netdom cannot be used to create a forest trust between two AD DS forests. To create a cross forest trust between two AD DS forests, you can either use a scripting solution or the Active Directory Domains and Trusts snap-in.
Very encouraging! :o)
Well, the first one was a failed attempt, but the second one with PowerShell was a success. I decided to use technic without importing any additional PS module, which is .Net
System.DirectoryServices.ActiveDirectory.Forest class and Forest.CreateTrustRelationship method.
Note: You have to run this script from local forest (trusted/inbound) under domain admin security context.
The final PS script is here:

# Change following parameters
$strRemoteForest = "forestName1.cz"
$strRemoteAdmin = "adminAccountName"
$strRemoteAdminPassword = "Heslo@123"

$remoteContext = New-Object -TypeName "System.DirectoryServices.ActiveDirectory.DirectoryContext" -ArgumentList @( "Forest", $strRemoteForest, $strRemoteAdmin, $strRemoteAdminPassword)
try {
        $remoteForest = [System.DirectoryServices.ActiveDirectory.Forest]::getForest($remoteContext)
        #Write-Host "GetRemoteForest: Succeeded for domain $($remoteForest)"
    }
catch {
        Write-Warning "GetRemoteForest: Failed:`n`tError: $($($_.Exception).Message)"
    }
Write-Host "Connected to Remote forest: $($remoteForest.Name)"
$localforest=[System.DirectoryServices.ActiveDirectory.Forest]::getCurrentForest()
Write-Host "Connected to Local forest: $($localforest.Name)"
try {
        $localForest.CreateTrustRelationship($remoteForest,"Inbound")
        Write-Host "CreateTrustRelationship: Succeeded for domain $($remoteForest)"
    }
catch {
        Write-Warning "CreateTrustRelationship: Failed for domain $($remoteForest)`n`tError: $($($_.Exception).Message)"
    }

Enjoy Jan

Sort by: Published Date | Most Recent | Most Useful
Comments
  • Hello,

    Excellent script. I have only one note about that. Here is an error within first meaningfull line.

    Instead of New-Object("Forest",$strRemoteForest,$strRemoteAdmin,$strRemoteAdminPassword)

    There should be NewObject -TypeName "System.DirectoryServices.ActiveDirectory.DirectoryContext" -ArgumentList @("forest", $strRemoteForest, $strRemoteAdmin, $strRemoteAdminPassword)

    Thanks & Regards,

    Stanislaw

  • Stanislaw Wawszczak edited Revision 2. Comment: I just implemented the bug fix from my comment.

Page 1 of 1 (2 items)