Delete Computers From SCCM Using POWERSHELL

In this post we will learn deleting computers from sccm console. Recently we have got a request from customer to delete 500+ machines from sccm. So we have created a script to delete bulk machines from SCCM

SCRIPT

<# This script will read notepad file for client computers, check if they exist and remove from SCCM .#>

# Determine script location and create log file to store the results

$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path

$log = "$ScriptDir\clientremoval.log"

$date = Get-Date -Format "dd-MM-yyyy hh:mm:ss"

"-------- Script executed on $date (dd-MM-yyyy hh:mm:ss) -------" + "`r`n" | Out-File $log -append

#try import SCCM Module ,if error catch it.

Try
{
Import-Module (Join-Path $(Split-Path $env:SMS_ADMIN_UI_PATH)    ConfigurationManager.psd1)

$SiteCode = Get-PSDrive -PSProvider CMSITE

$SMSProvider=$sitecode.SiteServerSet-Location "$($SiteCode.Name):\"
}
Catch
{
"[ERROR]`t SCCM Module couldn't be loaded. Script will exit!" | Out-File $log -append Exit 1
}

# Read the notepad file for client records

ForEach ($client in Get-Content $ScriptDir"\client.txt")
{

$CN=Get-CMDevice -Name $client
$name=$CN.Name
if($name)
{
try
{
"$date [INFO]`t $name found in SCCM " | Out-File $log -append  Remove-CMDevice -name $client -force
"$date [INFO]`t $name removed from SCCM " | Out-File $log -append  }
catch {"$date [INFO]`t $name found in SCCM but unable to delete record. Check further " | Out-File $log -append }
}
else
{
"$date [INFO]`t $client not found in SCCM " | Out-File $log append}
} 

Save above script .ps format. Once saved, create a notepad Client.txt. Client.txt will be used to input machines which needs to be deleted.

This script will take machines from notepad and check the availability in sccm. Devices will be removed if it is available in sccm console. Below tages will explain key functions in Script

ForEach ($client in Get-Content $ScriptDir”\client.txt”) =Read the notepad file for client records 

 $CN=Get-CMDevice -Name $client = check if device is available in console or not

Remove-CMDevice -name $client -force= Removing the device from sccm

Recently we had created another script for remote triggering of software updates via sccm. https://howtosccm.com/sccm/sccm-script-to-invoke-sccm-software-update-remotely/

Leave a Comment