Networknet archive Blog

PowerShell: Join a computer to Active Directory and rename its hostname

Originally published

The more you use PowerShell, the easier it becomes to build complex scripts and automate your processes. I like being able to copy scripts from OneNote and reuse them. My preference is to prepare the lab, work out the design and then recreate it in production with PowerShell and other unattended scripts.

There are thousands of PowerShell cmdlets for Windows clients, servers and BackOffice. The following script has helped me automate part of my virtual machine provisioning process: joining the computer to the domain, replacing the hostname generated by Windows Setup and rebooting the server.

I create the virtual machines manually, and joining each one to the domain takes many clicks. This script handles that work for me. In Hyper-V Manager, it can be pasted directly into the virtual machine through the console options.

Join the domain and rename the computer

PowerShell9 lines
1
2
3
4
5
6
7
8
9
# Set windows credential
$SetCredential = Get-Credential
# Join the computer to the domain
Add-Computer -DomainName networknet.nl -Credential $SetCredential
# Get Computername and Rename with WMI
$Computer = Get-WmiObject Win32_ComputerSystem
$Computernamenew = $Computer.Rename("NETWK-WEB-01", $SetCredential .GetNetworkCredential().Password, $SetCredential .Username)
#Reboot computer to apply new settings
Restart-Computer