Perrypackettracer / Powershell-scripts-to-use-in-an-active-directory

0 stars 0 forks source link

Delete users in AD #11

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

Automating the deletion of user accounts requires careful consideration, as it can have significant consequences. Ensure that you have proper backup and verification mechanisms in place before implementing such automation. Below is a simple PowerShell script that you can use as a basis for automating the deletion of user accounts based on certain criteria. The script uses the Remove-ADUser cmdlet to delete Active Directory user accounts.

# Import Active Directory module
Import-Module ActiveDirectory

# Set the criteria for user deletion (in this example, users who haven't logged in for 90 days)
$InactiveDaysThreshold = 90
$CurrentDate = Get-Date
$InactiveDate = $CurrentDate.AddDays(-$InactiveDaysThreshold)

# Get a list of inactive users
$InactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $InactiveDate} -Properties LastLogonDate

# Delete inactive users
foreach ($User in $InactiveUsers) {
    $UserName = $User.SamAccountName
    $UserDisplayName = $User.DisplayName

    # Uncomment the line below to actually delete the user (use with caution)
    # Remove-ADUser -Identity $UserName -Confirm:$false

    Write-Host "User $UserDisplayName ($UserName) has been deleted."
}

Explanation:

  1. Set the $InactiveDaysThreshold variable to define the number of days of inactivity that should trigger user deletion.

  2. The script uses the Get-ADUser cmdlet to retrieve a list of users who haven't logged in for the specified number of days.

  3. For each inactive user, the script prints information about the user and optionally deletes the user account. The Remove-ADUser line is commented out to prevent accidental deletion. Uncomment this line when you are certain about the deletion.

  4. Ensure that the script is executed with appropriate permissions to delete users in Active Directory.

Remember to test this script in a safe environment before using it in a production setting. Additionally, consider implementing additional checks and safeguards to prevent unintended deletions.