This code i made to be able to make a cleanup task for PC’s no longer in use. This script remove computers from domain when running WinPE.
This was one of the steps that was done. Another step deleted objects in McAfee EPO and SCCM.
To be able to delete a PC within a domain from a non-domain PC you need to install ADSI on the WinPE image.
You need this in order to make it work:
1. ADSI WinPE implementation: ADSI implementation in WinPE
2. You need a user with the right privileges on the AD server. The username should be provided with the domain name like this: “domain\username”
3. IP adresse to the AD server.
<#
.SYNOPSIS
.DESCRIPTION
.PARAMETER
.EXAMPLE
.NOTES
Author: Morten Rnborg
Date: 10-09-2018
Last Updated: 03-02-2019
https://mroenborg.com
#>
################################################
function Delete-PCInAD
{
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$PCName,
[Parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$ADIPAdress,
[Parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$UserName,
[Parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$Password
)
try
{
$objConn = New-Object -com "ADODB.Connection"
$objCommand = New-Object -com "ADODB.Command"
$objConn.Provider = "ADsDSOObject"
$objConn.Properties.Item("User ID").Value = $UserName
$objConn.Properties.Item("Password").Value = $Password
$objConn.Properties.Item("Encrypt Password").Value = $True
$objConn.Properties.Item("ADSI Flag").Value = 1
$objConn.Open("Active Directory Provider")
$objCommand.ActiveConnection = $objConn
$objCommand.CommandText = "SELECT ADsPath FROM 'LDAP://" + $ADIPAdress + "' WHERE objectCategory='computer' AND Name='" + $PCName + "'"
$objData = $objCommand.Execute()
$objData.MoveFirst()
$objADSPath = $objData.Fields.Item("ADsPath").Value
Write-Host ("ADSpath is about to be deleted: " + $objADSPath)
$domaininfo = new-object DirectoryServices.DirectoryEntry($objADSPath, $UserName, $Password)
$searcher = New-Object System.DirectoryServices.DirectorySearcher($domaininfo)
$computer = $searcher.FindOne()
$compdel = $computer.GetDirectoryEntry()
$compdel.DeleteTree()
Write-Host ("PC:" + $PCName +" successfully deleted.")
}
catch
{
Write-Host ("Deletion of Computer object in AD failed '" + $PCName + "' failed with error: {0}" -f $Error.Exception)
}
}
Leave a Reply