How to Remove a Computer From a Domain Using PowerShell

In the sophisticated ecosystem of IT management, ensuring that devices are correctly joined to or removed from a network domain is fundamental. For IT professionals, this task is usually repetitive, but the importance of seamless execution cannot be overstated. Today, we’re diving into a PowerShell script designed to remove a computer from a domain effortlessly.

Background

The script provided caters to the specific need of automating domain egress operations. Domains serve to conglomerate user accounts, computers, and group policies under one centralized roof. There are various reasons an IT professional might want to remove a computer from a domain, be it security, infrastructure changes, or hardware decommissioning. Manually doing this task is not only time-consuming but prone to human error. Therefore, a robust PowerShell script like the one above is invaluable to IT professionals and Managed Service Providers (MSPs).

The Script

#Requires -Version 2.0

<#
.SYNOPSIS
    Removes the computer from the domain.
.DESCRIPTION
    Removes the computer from the domain.
.EXAMPLE
     -UserName "MyDomainUser" -Password "Somepass1" -LocalUserName "Administrator" -LocalPassword "Somepass1"
    Removes the computer from the domain and restarts the computer.
.EXAMPLE
     -UserName "MyDomainUser" -Password "Somepass1" -LocalUserName "Administrator" -LocalPassword "Somepass1" -NoRestart
    Removes the computer from the domain and does not restart the computer.
.EXAMPLE
    PS C:> Leave-Domain.ps1 -UserName "MyDomainUser" -Password "Somepass1" -LocalUserName "Administrator" -LocalPassword "Somepass1" -NoRestart
    Removes the computer from the domain and does not restart the computer.
.OUTPUTS
    String[]
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2012
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    # Use a Domain UserName to remove this computer to a domain, this requires the Password parameter to be used as well
    [Parameter(Mandatory = $true)]
    [String]
    $UserName,
    # Use a Domain Password to remove a computer from a domain
    [Parameter(Mandatory = $true)]
    $Password,
    # Use a local admin's UserName to remove this computer from a domain, this requires the Password parameter to be used as well
    [Parameter(Mandatory = $true)]
    [String]
    $LocalUserName,
    # Use a local admin's Password to remove this computer from a domain
    [Parameter(Mandatory = $true)]
    $LocalPassword,
    # Do not restart computer after leaving to a domain
    [Switch]
    $NoRestart
)
    
begin {
    Write-Output "Starting Leave Domain"
    
    # Converts username and password into a credential object
    $LeaveCred = [PSCredential]::new($UserName, $(ConvertTo-SecureString -String $Password -AsPlainText -Force))
    
    # Converts username and password into a credential object
    $LocalCred = [PSCredential]::new($LocalUserName, $(ConvertTo-SecureString -String $LocalPassword -AsPlainText -Force))
}
    
process {
    Write-Output "Removing computer($env:COMPUTERNAME) from domain"
    $script:LeaveResult = $false
    try {
        $LeaveResult = if ($NoRestart) {
            (Remove-Computer -UnjoinDomainCredential $LeaveCred -PassThru -Force -LocalCredential $LocalCred -Confirm:$false).HasSucceeded
            # Do not restart after leaving
        }
        else {
            # Restart after leaving
            (Remove-Computer -UnjoinDomainCredential $LeaveCred -PassThru -Force -Restart -LocalCredential $LocalCred -Confirm:$false).HasSucceeded
        }    
    }
    catch {
        Write-Error "Failed to Leave Domain"
    }
    if ($LeaveResult) {
        if ($NoRestart) {
            Write-Output "Removed computer($env:COMPUTERNAME) from domain and not restarting computer"
        }
        else {
            Write-Output "Removed computer($env:COMPUTERNAME) from domain and restarting computer"
        }
    }
    else {
        Write-Output "Failed to remove computer($env:COMPUTERNAME) from domain"
        # Clean up credentials so that they don't leak outside this script
        $LeaveCred = $null
        $LocalCred = $null
        exit 1
    }
}
    
end {
    # Clean up credentials so that they don't leak outside this script
    $LeaveCred = $null
    $LocalCred = $null
    Write-Output "Completed Leave Domain"
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script follows a modular approach, encompassing three main sections – begin, process, and end.

  • In the begin section, it initializes the script, accepts parameters like domain and local usernames/passwords, and constructs credential objects from these parameters.
  • The process section is where the actual operation occurs. It uses the Remove-Computer cmdlet of PowerShell, a powerful tool designed to remove the computer from its current domain. The flexibility of the script allows for the option to restart the computer post-removal or leave it running, depending on the user’s preference.
  • The end section is about cleanup, ensuring the credentials used are wiped to prevent any potential security issues.

Potential Use Cases

Imagine an IT professional, Alex, managing the network infrastructure for a mid-sized organization. They have just decommissioned several old workstations, replacing them with new ones. Instead of manually disjoining each computer from the domain, Alex uses this script, saving hours of work, ensuring no residual credentials are left on the decommissioned machines.

Comparisons

While the GUI-based method, done through ‘System Properties’, offers a more visual approach, the PowerShell script excels in automation, scalability, and precision. For removing a single computer, the GUI might suffice, but for bulk operations, PowerShell stands unrivaled.

FAQs

  • Do I need administrative privileges to run this script? Yes, removing a computer from a domain requires administrative privileges both on the local machine and the domain.
  • What happens if I don’t provide the -NoRestart switch? By default, the computer will restart after being removed from the domain.

Implications

Using scripts like this to manage domain operations is not just a matter of convenience but of security. Ensuring that credentials don’t leak, as the script rightly does, is of paramount importance. A mismanaged domain removal can leave loopholes for cyber attackers.

Recommendations

  • Always test the script in a controlled environment before deploying in a live scenario.
  • Ensure that backup mechanisms are in place, especially when making bulk changes.
  • Regularly update the script to accommodate changes in the OS or PowerShell cmdlets.

Final thoughts

While PowerShell scripts like the one discussed offer immense utility, leveraging platforms like NinjaOne can further streamline IT operations. NinjaOne provides a unified IT monitoring and management platform, seamlessly integrating scripts, automation, and a plethora of IT tasks under one roof. For professionals looking to optimize their IT management tasks, tools like this script, when integrated with platforms like NinjaOne, offer a promising horizon.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).