Forum Discussion
tincho1984
Jan 23, 2024Copper Contributor
Add to the search of inactive users multiple OUs
Hi all I came with a script that works fine what it does is to find users that haven't logged on in more than 90 days in an specific OU and then it disables them, however I need the script to search...
- Jan 23, 2024
tincho1984 Could you try this?
#Script to disable users that not login for more than 90 days #Create the report file $FileName = "DisabledUsers" + (Get-Date).ToString("dd-MM-yyyy") + ".csv" New-Item -Path "C:\temp" -Name $FileName -ItemType File Add-Content -Path C:\temp\$fileName -Value "Account,Disabled date,Last Logon Date" $DisabledDate = Get-Date -Format dd/MM/yyyy $OUS="OU1","OU2" foreach ($OU in $OUS) { $UsersToDisable = Get-ADUser -Filter 'Enabled -eq $True' -SearchBase "$($OU)" -Properties LastLogonDate,WhenCreated | where {$_.LastLogonDate -lt (get-date).AddDays(-90) -and $_.WhenCreated -lt (get-date).AddDays(-90)} foreach($User in $UsersToDisable){ if($User.DistinguishedName -notlike "$($OU)"){ Disable-ADAccount -Identity $User.SamAccountName -Confirm:$false if((Get-ADUser -Identity $User.SamAccountName)){ $Account = $User.SamAccountName $LastLogon = $User.LastLogonDate $Value = "$Account,$DisabledDate,$LastLogon" Add-Content -Path C:\temp\$FileName -Value $Value } } } }
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.
If one of the posts was helpful in other ways, please consider giving it a Like.
Jan 23, 2024
tincho1984 Could you try this?
#Script to disable users that not login for more than 90 days
#Create the report file
$FileName = "DisabledUsers" + (Get-Date).ToString("dd-MM-yyyy") + ".csv"
New-Item -Path "C:\temp" -Name $FileName -ItemType File
Add-Content -Path C:\temp\$fileName -Value "Account,Disabled date,Last Logon Date"
$DisabledDate = Get-Date -Format dd/MM/yyyy
$OUS="OU1","OU2"
foreach ($OU in $OUS) {
$UsersToDisable = Get-ADUser -Filter 'Enabled -eq $True' -SearchBase "$($OU)" -Properties LastLogonDate,WhenCreated | where {$_.LastLogonDate -lt (get-date).AddDays(-90) -and $_.WhenCreated -lt (get-date).AddDays(-90)}
foreach($User in $UsersToDisable){
if($User.DistinguishedName -notlike "$($OU)"){
Disable-ADAccount -Identity $User.SamAccountName -Confirm:$false
if((Get-ADUser -Identity $User.SamAccountName)){
$Account = $User.SamAccountName
$LastLogon = $User.LastLogonDate
$Value = "$Account,$DisabledDate,$LastLogon"
Add-Content -Path C:\temp\$FileName -Value $Value
}
}
}
}
Please click Mark as Best Response & Like if my post helped you to solve your issue.
This will help others to find the correct solution easily. It also closes the item.
If one of the posts was helpful in other ways, please consider giving it a Like.
- tincho1984Jan 24, 2024Copper Contributor
Thanks a lot for all your help 🙂
Cheers!