0
I am working on an AD cleanup script but am having trouble getting it to work correctly. The parameters that I am attempting to meet are User has not logged in for the past 90 days and was created before 90 days ago. The problem is that it is getting users that were created within the past 90 days. Here is the script I am working on:
Import-Module ActiveDirectory
$OU="ou=Users,ou=middle,ou=top,dc=contoso,dc=com"
$CSV_USERS=""
foreach ($x in $OU) {
$USERS=Search-ADAccount -AccountInactive -Timespan 90.00:00:00 -Searchbase $x | Where {$_.whenCreated -le ((Get-Date).AddDays(-90).toFileTime())}
if ($USERS) {
$CSV_USERS=$CSV_USERS + $USERS
}
}
$date=Get-Date -Format "dMy"
$path="C:\Scripts\TestScript_disable_users_"+$date+".csv"
if($CSV_USERS) {
Out-File -FilePath $path -InputObject $CSV_USERS
}
Once the script works properly I will add the following lines under the $CSV_USERS=$CSV_USERS + $USERS
$USERS | Disable-AdAccount
$USERS | Move-AdObject -TargetPath "OU=Inactive employees,dc=contoso,dc=com"
Can anyone help me find out why the "| Where" parameters are not working for me?
there's no
whenCreated
property. and it also doesn't make sense. ifsearch-adaccount -accountinactive -timespan 90
returns users, these users have to be created longer than 90 days ago, otherwise it wouldn't return them because of the timespan. so you don't need yourwhere
. change your timepan to90
instead of90.00:00:00
and it should work properly – SimonS – 2017-01-06T13:35:23.643@Greg what error or results are you getting? There is a WhenCreated Property in AD but Search-Adaccount doesn't return. You need a second call to AD for that. – uSlackr – 2017-01-06T14:30:29.580
It looks like you have created a second account, which will also interfere with your ability to comment within your thread and to accept an answer. See How can one link/merge/combine/associate two accounts/users? and/or I accidentally created two accounts; how do I merge them? for guidance on how to merge your accounts.
– DavidPostill – 2017-01-07T12:07:56.210