have prepared a script to find and disabled AD users who are inactive for 40 days. I want the script output file to include the DisplayName of the accounts that got disabled by each run.
Ex:
Daniel Andrews, Peter Huyen, Ashoka Handagama
When I run the script I get the following error:
Transcript started, output file is C:\temp\Test\Disable_and_Move_User_Accounts_20230522_11-15-37.log PS C:\WINDOWS\system32> TerminatingError(Set-ADUser): “The requested operation did not satisfy one or more constraints associated with the class of the object” Error occured updating account desmond_palima. The requested operation did not satisfy one or more constraints associated with the class of the object
The script I developed is as follows. Can you please help me to fix it?
Import-Module ActiveDirectory
$inactiveDays = 40
$disableDaysInactive=(Get-Date).AddDays(-($inactiveDays))
$todaysDate = (Get-Date -format "yyyyMMdd_HH-mm-ss")
$LogFile = "C:\temp\Test\Disable_and_Move_User_Accounts_$todaysDate.log"
$DisabledOU = 'OU=Test Disable,OU=User Accounts,OU=Car,DC=car,DC=com'
$path= "OU=Test,OU=User Accounts,OU=Car,DC=car,DC=com"
$userlist = Get-ADUser -SearchBase $path -Filter {(Enabled -eq $True)} -Properties * | Where-Object {($_.description -Notlike "*Service Account*") -and ($_.lastLogonDate -lt $disableDaysInactive) -and ($_.lastLogonDate -ne $NULL)}
Start-Transcript -path $LogFile
if ($userlist) {
ForEach ($user in $userlist){
$desc = "Disabled on $(Get-Date) for being inactive for 40 days $($user.Description)"
try {
Set-ADUser -Identity $user -Description $desc -Enabled $false
Move-ADObject -Identity $user -TargetPath $DisabledOU
Write-Output $user.DisplayName
}
catch {
'Error occured updating account {0}. {1}' -f $user.SamAccountName, $_ } }}
else { "No users met the search criteria."
}