Overview
This PowerShell script automates the deletion of computer objects from Active Directory based on a list of device names. It reads the device names from a specified text file and attempts to delete each corresponding computer object from AD, while logging the outcome for each device.
Instructions
- Prepare the Device List:
- Create a text file named
device_list.txt
in theC:\Logs
directory, containing the names of the devices you want to delete (one device name per line).
- Create a text file named
- Copy the Script:
- Save the following script to a
.ps1
file (e.g.,DeleteDevices.ps1
).
# Define the path to the text file containing the list of device names $deviceListPath = "C:\Logs\device_list.txt" # Read the device names from the text file $deviceNames = Get-Content $deviceListPath # Create a log file to save the output $logFile = "C:\Logs\device_deletion_log.txt" # Iterate through each device name foreach ($deviceName in $deviceNames) { # Find the device object in AD $device = Get-ADComputer -Filter { Name -eq $deviceName } # Check if the device object exists if ($device) { # Delete the device from AD Remove-ADComputer -Identity $device -Confirm:$false $message = "Device '$deviceName' deleted from Active Directory." Write-Host $message $message | Out-File -Append $logFile } else { $message = "Device '$deviceName' not found in Active Directory." Write-Host $message $message | Out-File -Append $logFile } } Write-Host "Device deletion process completed. Logs saved to: $logFile"
- Save the following script to a
- Run the Script:
- Execute the
DeleteDevices.ps1
script with appropriate permissions. - The script will delete the devices listed in
device_list.txt
and log the results indevice_deletion_log.txt
.
- Execute the
Script Explanation
- Reading the Device List:
The script reads the device names from
device_list.txt
, which should be located in theC:\Logs
directory. - Deleting Devices:
The script checks if each device exists in Active Directory and, if so, deletes it.
- Logging:
Each deletion attempt (successful or unsuccessful) is logged to
device_deletion_log.txt
, providing a record of the operation.
Tags:
#PowerShell #ActiveDirectory #Automation #Scripting #SystemAdministration