I have a domain controller setup for testing purposes with one Windows 10 workstation joined to the domain.
Let's say I want to remove the current DC and deploy a new one with the same IP, but a different domain name.
Using a PowerShell script, Remove-Computer will only succeed if the domain controller is powered off, or a firewall rule is in place blocking comms to the DC.
How can I automate and successfully unjoin a workstation using PowerShell without having to first power off the DC or add a firewall rule?
Here is the script I'm using to leave a domain (if already joined to one) and then join the new domain.
Write-Host "Attempting to join this workstation to the domain..."
$password = ConvertTo-SecureString 'mypassword' -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential ("HOMELAB\Administrator", $password)
$rule = Get-NetFirewallRule -DisplayName DOMAINCONTROLLER -ErrorAction SilentlyContinue
$isDomainMember = (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
if ($isDomainMember) {
Write-Host "Leaving domain..."
if($rule -eq $null) {
Write-Host "Adding firewall rule to block domain"
$addrule = New-NetFirewallRule -DisplayName DOMAINCONTROLLER -Direction Outbound –LocalPort Any -Protocol TCP -Action Block -RemoteAddress 192.168.239.144
}
$result = Remove-Computer -PassThru -Force -ErrorAction SilentlyContinue
}
if (Get-NetFirewallRule -DisplayName DOMAINCONTROLLER -ErrorAction SilentlyContinue) {
Write-Host "Removing firewall rule"
Remove-NetFirewallRule -DisplayName DOMAINCONTROLLER
}
$join = Add-Computer -DomainName homelab.local -Credential $credentials -PassThru -ErrorAction SilentlyContinue
if ($join.HasSucceeded) {
Write-Host -BackgroundColor Green -ForegroundColor Yellow "Success!"
} else {
Write-Host -BackgroundColor Red -ForegroundColor Yellow "Fail"
}
Thanks!