Search code examples
active-directorypowershell-3.0

Powershell script to confirm an account from a CSV is disabled before deleting the account


Hi I hope someone can help me, I'm not great at scripting and my issue is...

I have a medium estate of around 15,000 users which is in a bit of a mess. There are around 3000 user accounts which are disabled. Some user accounts are disabled due to the user being on long term sick, maternity, or suspended, these 'known' accounts are not to be touched so I cannot do a broad "find accounts that are disabled and just delete them" script.

Currently I have a script which exports all disabled accounts to a csv, I then manually manipulate that data within the csv to tag known accounts that cannot be deleted. I then take that file and run this script...

Import-Module ActiveDirectory
$list = Import-CSV C:\temp\deleteuser.csv

forEach ($item in $list) {
    $samAccountName = $item.samAccountName

    #Get DistinguishedName from SamAccountName
    $DN = Get-ADuser -Identity $Samaccountname -Properties DistinguishedName |
        Select-Object -ExpandProperty DistinguishedName
 try{
    #Remove object using DN
    Remove-ADObject -Identity $DN -Confirm:$false
    "Remove successful for $SamAccountName" | Out-File 'C:\temp\Account Delete Success.txt' -Append }
Catch{
     "Remove failed for $SamAccountName" | Out-File 'C:\temp\Account Delete Failed.txt' -Append
}
}

While this is great, I'd love to be able to check the user account is still disabled before the Remove-ADObject command is run and for it to skip the account and output the name of the skipped account to a txt file. Is that possible or am I over complicating things?


Solution

  • simply test 'Enabled' property before deleting user like this :

    Import-Module ActiveDirectory
    $list = Import-CSV C:\temp\deleteuser.csv
    
    forEach ($item in $list) {
        $samAccountName = $item.samAccountName
        
        #Get DistinguishedName from SamAccountName
            
        $DN = Get-ADuser -Identity $Samaccountname -Properties DistinguishedName, Enabled |
        Select-Object -ExpandProperty DistinguishedName
        try{
            #Remove object using DN
            if (!$DN.Enabled){
                Remove-ADObject -Identity $DN -Confirm:$false
            "Remove successful for $SamAccountName" | Out-File 'C:\temp\Account Delete Success.txt' -Append }
            else {
            "Remove aborted for $SamAccountName" | Out-File 'C:\temp\Account Delete aborted.txt' -Append }
                }
        }
        Catch{
            "Remove failed for $SamAccountName" | Out-File 'C:\temp\Account Delete Failed.txt' -Append
        }
    }