Powershell to find and disable and delete user accounts

Hi all,

I am new to Powershell, and have been given the task to do the following.

I am trying to get a PowerShell script v4 to got through certain OU Groups in AD and if a user is 60 days inactive then disable it and move to a disabled OU, if inactive 90 day or more then delete the from the disabled OU.


I have this so far, with the Transcript, I have it in there to log, but I can not get it to format correctly.

Also need to move the users profile folder to a drive, where we will keep it for a period of time before deleting.

$Logfile = "D:\test\AUTODELETEUSERS.txt"

Start-Transcript -Path $Logfile 

Write-Verbose "START OF LOG FILE" -Verbose

Write-Verbose "Compare Date : Getting date" -Verbose


Write-Verbose "Settings Number of days to 60" -Verbose






$OnLeave='On Leave Until'



$then = (Get-Date).AddDays(-60)

$LISTOFACCOUNTS=Get-ADUser -Property Name,lastLogonDate -Filter {lastLogonDate -lt $then} -SearchBase $OU | FT Name,lastLogonDate








    IF (($USER.Notes -notlike '*'+$OVERRIDE+'*') -and ($USER.Description -notlike '*'+$OnLeave+'*')) 


        REMOVE-ADOBJECT $USER.Name -whatif 

        WRITE-HOST $USER.Name 'Deleted' 


    ELSEIF ($USER.Notes -like '*'+$OVERRIDE+'*') 


            WRITE-HOST $USER.Name 'Not removed due to Administrative Override' 




            WRITE-HOST $USER.Name 'Not removed - Presently on Leave' 




$Name = "testuser"

$User = Get-ADUser -LDAPFilter "(sAMAccountName=$Name)"

If ($User -eq $Null) {"User does not exist in AD"}

Else {"User Found in AD"}

Get-ADUser -Filter * -SearchBase $OU -Properties Enabled, CanonicalName, Displayname,Givenname, Surname, Department  | select Enabled, 

CanonicalName, Displayname, GivenName, Surname, Department | Export-CSV "E:\Damo\UserDescription.csv"

0 Comments   [ + ] Show comments

Answers (1)

Answer Summary:
Posted by: JackNeff 7 years ago
White Belt

G'day mate!  You probably already figured it out by now but thought I'd post in case it helps someone else.  

For logging I like to use the old ">>" to a text file because it's fast and easy.  Can't help you much with backing up user profiles because I don't know where you're storing them in your environment.

#Declare variable constants[string]$Log = "D:\test\AUTODELETEUSERS.txt"[int]$DaysToDisable = -60[int]$DaysToDelete = -90[string]$SearchBaseOU = 'OU=Test,DC=corporate,DC=nzpost,DC=co,DC=nz'[string]$DisabledOU = 'OU=Disabled,OU=Test,DC=corporate,DC=nzpost,DC=co,DC=nz'[string]$OverrideKey = '***OVERRIDE***'[string]$OnLeaveKey = 'On Leave'[int]$CountDisabled = 0[int]$CountDeleted = 0"[SCRIPT START] Script started on $(Get-Date)" >> $Log#DELETE stale accountsGet-ADUser -SearchBase $SearchBaseOU -SearchScope Subtree -Filter * -Properties * |     where { (([DateTime]::FromFileTime($_.LastLogon)) -lt (Get-Date).AddDays($DaysToDelete)) -and             ($_.Notes -notmatch $OverrideKey) -and             ($_.Description -notmatch $OnLeaveKey) } | ForEach-Object {        $_ | Remove-ADUser -WhatIf        "  [DELETED] $($UserAccount.Name)" >> $Log        $CountDisabled++    }#DISABLE stale accountsGet-ADUser -SearchBase $SearchBaseOU -SearchScope Subtree -Filter * -Properties * |     where { (([DateTime]::FromFileTime($_.LastLogon)) -lt (Get-Date).AddDays($DaysToDisable)) -and             ($_.Notes -notmatch $OverrideKey) -and             ($_.Description -notmatch $OnLeaveKey) } | ForEach-Object {        $_ | Move-ADObject -TargetPath $DisabledOU -WhatIf        $_ | Disable-ADAccount        "  [DISABLED] $($_.Name) for being $(((Get-Date)-([DateTime]::FromFileTime($_.LastLogon))) | select -ExpandProperty Days) days stale" >> $Log        $CountDeleted++    }"[SCRIPT END] $($CountDisabled) accounts disabled and $($CountDeleted) accounts deleted." >> $Log

Don't be a Stranger!

Sign up today to participate, stay informed, earn points and establish a reputation for yourself!

Sign up! or login

View more:


This website uses cookies. By continuing to use this site and/or clicking the "Accept" button you are providing consent Quest Software and its affiliates do NOT sell the Personal Data you provide to us either when you register on our websites or when you do business with us. For more information about our Privacy Policy and our data protection efforts, please visit GDPR-HQ