0

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!

  • 1
    Can you share the error that appears when you try to leave the domain ? – Swisstone Apr 12 '20 at 12:06
  • If you join or disjoin a machine from a domain it must be rebooted once after either action in order to establish it's trust or remove it. As well, your SID's will be a mess. So, join it, reboot it, disjoin it. It will work. your set-netfirewallrule command is bad. use -displaygroup and do NOT specify inbound our outbound. That relationship is synchronous, not asynchronous. – Citizen Apr 24 '20 at 00:41

0 Answers0