Pete Hinchley: Add a Computer to a Domain using PowerShell

The following PowerShell command will add a computer to the "Servers" organisational unit within the domain "lab.hinchley.net", and initiate an automatic reboot:

Add-Computer -DomainName "lab.hinchley.net" -OUPath "ou=Servers,dc=lab,dc=hinchley,dc=net" -Credential (Get-Credential lab\administrator) -Restart -Force

Note: The command will fail if a matching computer account already exists in the domain under a different organisational unit. This issue can be avoided by checking for the existence of the computer account prior to calling the Add-Computer cmdlet, and if the computer exists, moving the existing object to the correct location.

The task is made slightly more complicated by two factors: firstly, we can't rely on the Get-AdComputer cmdlet to search for the account, as it is unlikely the computer will have the Active Directory PowerShell module installed; and secondly, because the computer isn't on the domain, we will need to explicitly connect to Active Directory using domain credentials.

Here is some sample code:

$Domain = "lab.hinchley.net"
$Server = "MOLLY"
$OU = "ou=Servers,dc=lab,dc=hinchley,dc=net"

$Credential = Get-Credential
$NetCredential = $Credential.GetNetworkCredential()

$Username = "{0}\{1}" -f $NetCredential.Domain, $NetCredential.Username
$Password = $NetCredential.Password

$DomainInfo = New-Object DirectoryServices.DirectoryEntry("LDAP://$Domain", $Username, $Password)

$Search = New-Object DirectoryServices.DirectorySearcher($DomainInfo)
$Search.Filter = "(samAccountName=$($Server)$)"

if ($Comp = $Search.FindOne()) {
  $TargetOU = New-Object DirectoryServices.DirectoryEntry("LDAP://$Domain/$OU")
  $Comp.GetDirectoryEntry().MoveTo($TargetOU)
  Start-Sleep -Seconds 5
}

Add-Computer -DomainName $Domain -OUPath $OU -Credential $Credential -Restart -Force