I am trying to automate the following task in DC server via Task Scheduler.
Find the ad users who have not logged in for more than 40 days before 2023, disable them and move to the Disabled User OU. The Service Accounts filtered by the Description are excluded from the query. (Currently I manually check the Service Accounts from the csv file and exclude)
Currently I use a manual process with 3 queries as shown below:
i) Found AD account users via Powershell and get the list to a csv file.
It looks like you’ve spend a little effort to create your profile. You even uploaded a profile picture. Please spend a little more effort and fix the formatting of your code. Like it is now it is hard to distinguish between text and code.
When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.
Checking a users OU location with a if, the query has a SearchBase to only search a specific OU, not all of AD.
The TargetPath for Move-ADUser had a $ in it, should just be a path as a string.
When you do a loop, keep it singular (e.g. $user). The loop is looping against a collection, which would be plural. When someone sees $users in the loop, it’s confusing since your changing a single item with that token.
Another option for searching is Get-AdUser as it can filter for the description criteria as well. Do as much filtering in AD (general terms, it’s called filtering Left) so the script is not pulling 1000 records and then filtering client side to get to 10 records. For this, it’s fine as I’m sure there will not be too many Service Accounts, but in an ideal world $userList would only contain users that are required in the script.
Here is a cleaned up and untested script for reference. Note that -WhatIf is placed on the Set and Move command to make sure the script does what you want before you take action on any accounts by mistake:
Thank you for the refined transcript. It is mostly what I wanted. However, it does not capture users. It says “No users met the search criteria”. I think the searchAdParams not working.
I took your query, modified and inserted the “$userlist=…” with my own created part. It worked except for capturing the accounts that are inactive for more than 40 days. Instead, it disabled all the enabled users whose description is not set to “Service Accounts” Because I don’t know how to pass multiple parameters in that section.
Could you please help me to fix this section?
I want to make this section capture the Ad user accounts that are inactive for more than 40 days.
Before putting Set or Move or Remove cmdlets, best practice is to make sure the query is only returning what you want to change. Even the query is adjusted, I would add -WhatIf and only run the query section to validate the query is working without running the entire script.