DISABLING UNUSED AD ACCOUNTS

Mark Clayborough 0 Reputation points
2025-01-24T15:28:13.5233333+00:00

A script that used to work last year throws an error on -Identity

I am trying to disable accounts that have no longer been used in over 180 days and move them to a separate OU

#Disable ad user not logged in 180 days

#define Ou domain name

$ou="OU=CLIENTS,OU=XXX,DC=XXX,DC=com"

#define days days the period which users did not logged and you want to disable

$days=180

$exportedpath= "$env:userprofile\desktop\Inactive_Client_users_180.csv"

#define Disabled OU

$disabledou="OU= Clients_Inactive_Accounts,OU=Clients,OU=XXX,DC=XXX,DC=com"

get-aduser -filter 'enabled -eq $true' -SearchBase $ou -Properties samaccountname,lastlogondate | Where-object {$_.lastlogondate -lt (get-date).AddDays(-$days)} | Select-Object name,samaccountnamem,DistinguishedName| export-csv $exportedpath -nti

Run Cleanup

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null

$Response = [Microsoft.VisualBasic.Interaction]::InputBox("Verify the users by reading csv here$exportedpath if you are ready to disable users press Y ")

IF ($response -eq "Y")

{

import-csv $exportedpath| Foreach-Object {Get-ADUser $_.samaccountname | Set-ADUser -Enabled $false

}

}

ELSE

{

Write-Host "come back later " -f red

Exit

}

import-csv $exportedpath|ForEach-Object {

 # Retrieve DN of User. 

 **$UserDN  = (Get-ADUser -Identity $_.samaccountname).distinguishedName** 

 Write-Host " Moving Accounts ..... " 

 # Move user to target OU. 

 **Move-ADObject  -Identity $UserDN  -TargetPath $disabledou -Verbose}**

  

$total = (import-csv $exportedpath).count

  Write-Host "$total accounts have been processed successfully..." -ForegroundColor Green
Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,823 questions
0 comments No comments
{count} votes

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.