Posted On September 16, 2021

PowerShell: Unjoin Computer From Domain

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Unjoin Computer From Domain
# unjoinComputerFromDomain.ps1
# Version 0.02
# Notes:
# - This function doesn't delete the referenced computer account from Active Directory
# - Another function to purge AD Computer account will be required to completely tombstone object

# Windows domain variables
$computerNames=@(
    "$ENV:COMPUTERNAME"
)
$adminCred=get-credential $env:USERDOMAIN\$env:USERNAME
$workgroup='Archive'
$standardLocalAdminPassword='Password1'
 
function unjoinComputerFromDomain{
    param(
        $computernames=$env:computername,
        $adminCred,
        $standardLocalAdminPassword,
        $workgroup='Archive'
        )
  $username=$adminCred.UserName
  $securedPassword=$adminCred.Password
  $password=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securedPassword))                   
     
  $results=@()
  foreach ($computername in $computernames){
    $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:computername is NOT joined to any domain. No actions taken."
                  return $true
              }      
          } -Args $username,$password,$standardLocalAdminPassword,$workgroup -EA Stop
          $null=Remove-PSSession -ID $psSession.ID
          $results+=[hashtable]@{$computername=$result}
      }catch{
          write-warning $_
          $null=Remove-PSSession $psSession
          $results+=[hashtable]@{$computername=$false}
      }    
    }else{
      write-host "Unable to connect to $computername..."
      $results+=[hashtable]@{$computername=$false}
    }
    # this step should be unnecessary; It's here to ensure that propagation is complete
    if($(try{get-adcomputer -identity $computername -ea Ignore}catch{})){
      Remove-ADComputer -Identity $computername
    }
    pause
  }
  return $results
}
 
unjoinComputerFromDomain $computernames $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 *

Related Post

Basic HTML and HTML5: Uncomment HTML

<!--<h1>Hello World</h1><h2>CatPhotoApp</h2><p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase…

How To Format HTML Content For Email

Major email service providers such as Google Gmail and Microsoft Office 365 have been supporting…

PowerShell: Play with Time

1. Constructor: $timer=[System.Diagnostics.Stopwatch]::StartNew() 2. Accessing a property $totalSeconds=$timer.Elapsed.TotalSeconds 3. Output Time (Usage): $hours=[math]::round($totalSeconds/3600,2)write-host "It has…
Other project: DragonCoin.com