With PowerShell 2 this was done through WMI, specifically by using the Win32_ComputerSystem class and the attached JoinDomainOrWorkgroup method.
Here’s an example of how this could be done:
$comp = Get-WmiObject Win32_ComputerSystem
$password = "P@ssw0rd01"
$user = "test\jeffwouters"
$domain = "test"
$comp.JoinDomainOrWorkgroup($domain, $password, $user, $null, 3)
But now we’ve got PowerShell 3, right?
Within the humongous amount of new cmdlets, there is the Add-Computer cmdlet which allows you to join the computer to a domain or workgroup.
How you can do this? Fairly simple actually:
Add-Computer -ComputerName SCVMM01 -DomainName demo -OUPath "OU=Servers,DC=,DC=test,DC=lan" -Credential demo\jeffwouters -Restart
This command will use the current user to change the membership on the device, the domain credentials to join the device to the domain, place it in the correct OU and do a reboot to complete the process.
Don’t want to use the current user but you want to specify one? No problem, use the –LocalCredential parameter.
See how easy this has become?
But… what if you wanted to unjoin a server from a domain and rejoin it to another domain (a fairly common migration scenario)?
I won’t even post the VB code in there for that since that’s just spamming… nor will I post the PowerShell v2 code.
Let’s go straight to the PowerShell v3 solution for this:
Add-Computer –ComputerName SCVMM01 –Domain demo –LocalCredential test\jeffwouters –UnjoinDomainCredential test\jefwou –Credential demo\jeffwouters –Restart
See how the domain credential of the old domain is used as the local credential?
I’ve done this in this example to show you that domain credentials can be used as local credentials when the device is already a member of that domain.
So why would you use domain credentials for that? Easy… when you want to unjoin/join multiple devices with one single command:
Add-Computer –ComputerName SCVMM01, SCCM01, DPM01, SCOM01 –Domain demo –LocalCredential test\jeffwouters –UnjoinDomainCredential test\jefwou –Credential demo\jeffwouters –Restart