purple and green grass on gray sand

PowerShell Script to Delete Devices from Active Directory and Save Logs

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

  1. Prepare the Device List:
    • Create a text file named device_list.txt in the C:\Logs directory, containing the names of the devices you want to delete (one device name per line).
  2. 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"
  3. 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 in device_deletion_log.txt.

Script Explanation

  • Reading the Device List:

    The script reads the device names from device_list.txt, which should be located in the C:\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

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

WordPress Cookie Plugin by Real Cookie Banner