PowerShell: Unjoin Computer From Domain

# unjoinComputerFromDomain.ps1
# Version 0.02

# Windows domain variables
$computername='testwindows.intranet.kimconnect.com'
$adminCred=get-credential
$workgroup='Archive'
$standardLocalAdminPassword='Password1'

function unjoinComputerFromDomain{
    param(
        $computername,
        $adminCred,
        $standardLocalAdminPassword,
        $workgroup='Archive'
        )
  $username=$adminCred.UserName
  $securedPassword=$adminCred.Password
  $password=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securedPassword))                   
  $psSession=try{
    $psOptions=New-PSSessionOption -OpenTimeout 300 -CancelTimeout 300
    new-pssession -computername $computername -Credential $adminCred -SessionOption $psOptions
    write-host "Connected to $computername..."
  }catch{
    write-warning $_
    $false
  }
  if($psSession.State -eq 'Opened'){
    try{
        $result=invoke-command -session $psSession -scriptblock{
            param ($adminUsername,$adminPassword,$standardLocalAdminPassword,$workgroup)
            if ((gwmi win32_computersystem).partofdomain -eq $true) {
                $userdomain=$env:USERDNSDOMAIN
                $encryptedPassword=$(ConvertTo-SecureString $standardLocalAdminPassword -AsPlainText -Force)
                Set-LocalUser -name Administrator -Password $encryptedPassword
                write-host "The local 'Administrator' account password has been reset to the standard password: $standardLocalAdminPassword"
                $encryptedAdminPass=$(ConvertTo-SecureString $adminPassword -AsPlainText -Force)
                $adminCred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminUsername,$encryptedAdminPass
                try{
                    Remove-Computer -UnjoinDomaincredential $adminCred -PassThru -Verbose -Restart -WorkgroupName $workgroup -Force
                    write-host "$env:computername has been removed from $userdomain"
                    return $true
                }catch{
                    write-warning $_
                    return $false
                }
            }else{
                write-host "$env:computer is NOT joined to any domain. No actions taken."
                return $true
            }      
        } -Args $username,$password,$standardLocalAdminPassword,$workgroup -EA Stop
        $null=Remove-PSSession -ID $psSession.ID
        return $result
    }catch{
        write-warning $_
        $null=Remove-PSSession $psSession
        return $false
    }    
  }else{
    write-host "Unable to connect to $computername..."
    return $false
  }
  if(get-adcomputer -identity $computername -ea SilentlyContinue){
    Remove-ADComputer -Identity $computername
  }
}

unjoinComputerFromDomain $computername $adminCred $standardLocalAdminPassword $workgroup
# unjoinComputerFromDomain.ps1
# Version 0.01

$computername='testwindows'
$adminUsername='intranet\testadmin'
$adminPassword='PASSWORD'
$workgroup='Archive'

function unjoinComputerFromDomain{
    param(
        $computername,
        $adminUsername,
        $adminPassword,
        $workgroup='Archive'
        )
  $adminCred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminUsername,$(ConvertTo-SecureString $adminPassword -AsPlainText -Force)
  $psSession=try{
    $psOptions=New-PSSessionOption -OpenTimeout 300 -CancelTimeout 300
    new-pssession -computername $computername -Credential $adminCred -SessionOption $psOptions
    write-host "Connected to $computername..."
  }catch{
    write-warning $_
    $false
  }
  if($psSession.State -eq 'Opened'){
    try{
        $result=invoke-command -session $psSession -scriptblock{
            param ($adminUsername,$adminPassword,$workgroup)
            if ((gwmi win32_computersystem).partofdomain -eq $true) {
                $userdomain=$env:USERDNSDOMAIN
                $encryptedPassword=$(ConvertTo-SecureString $adminPassword -AsPlainText -Force)
                Set-LocalUser -name Administrator -Password $encryptedPassword
                write-host "The local 'Administrator' account password has been reset to be the same as the password of user $adminUsername"
                $adminCred=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminUsername,$encryptedPassword
                try{
                    Remove-Computer -UnjoinDomaincredential $adminCred -PassThru -Verbose -Restart -WorkgroupName $workgroup -Force
                    write-host "$env:computername has been removed from $userdomain"
                    return $true
                }catch{
                    write-warning $_
                    return $false
                }
            }else{
                write-host "$env:computer is NOT joined to any domain. No actions taken."
                return $true
            }      
        } -Args $adminUsername,$adminPassword,$workgroup -EA Stop
        $nullRemove-PSSession -ID $psSession.ID
        return $result
    }catch{
        write-warning $_
        $null=Remove-PSSession $psSession
        return $false
    }    
  }else{
    write-host "Unable to connect to $computername..."
    return $false
  }
}

unjoinComputerFromDomain $computername $adminUsername $adminPassword

Leave a Reply

Your email address will not be published. Required fields are marked *