Delete users in a OU after days

Matteo Carlini 0 Reputation points
2023-03-20T17:38:16.4733333+00:00

I adapted the script below to my needs.

I can't get the remove users part to work

$Days = 1280
$LastModified = (Get-Date).Adddays(-($Days))
$Users =Get-ADUser -filter {Enabled -eq $False} -SearchBase 'OU=DisabledAccount,DC=adr,DC=it' -properties WhenChanged  |
where {$_.WhenChanged -le (Get-Date).AddDays(-($Days))} | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, WhenChanged, DistinguishedName

ForEach ($Item in $Users){
    Remove-ADUser -Identity $Item.DistinguishedName -Confirm:$false
    Out-File -FilePath C:\Scripts\DeletedUsers.txt -Append
    }

Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
12,909 questions
Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,417 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,504 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,449 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,329 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 46,551 Reputation points
    2023-03-20T19:30:45.32+00:00

    You aren't writing anything to your log file. And you aren't doing any error checking (or logging). Try this:

    $Days = 1280
    $LastModified = (Get-Date).Adddays( - ($Days))
    $Users = Get-ADUser -Filter { Enabled -eq $False } -SearchBase 'OU=DisabledAccount,DC=adr,DC=it' -Properties WhenChanged  |
        Where-Object { $_.WhenChanged -le (Get-Date).AddDays( - ($Days)) } | 
            Select-Object @{ Name = "Username"; Expression = { $_.SamAccountName } }, Name, WhenChanged, DistinguishedName
    
    ForEach ($Item in $Users) {
        $dn = $Item.DistinguishedName
        Try{
            Remove-ADUser -Identity $Item.DistinguishedName -Confirm:$false -ErrorAction Stop
        }
        Catch{
            "DN = $dn was *NOT* removed`n`n$_" | Out-File -FilePath C:\Scripts\DeletedUsers.txt -Append
        }
        "DN = $DN WAS removed" |Out-File -FilePath C:\Scripts\DeletedUsers.txt -Append
    }
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.