Reputation: 31
I've tried to create a new powershell script that doesn't seem to be working for me. What I want it to do is to find all users in a specific Organizational Unit and then see if any of those users have not logged in for the last x number of days. After that I want each of those users to be disabled. I have not built the entire script yet, because I'm stuck at calculating whether or not a user has been logged in at all.
The script I have so far looks like this
import-module ActiveDirectory
$numdays = read-host 'provide the number of days user has not logged in'
$OUN = read-host 'provide the Organizational Unit name'
$nu = get-date -format dd-MM-yyyy-HH-mm-ss
$logfile = ".\$nu.txt"
$recent = @()
$oud = @()
$currentdate = [System.DateTime]::Now
$currentdateUTC = $currentdate.ToUniversalTime()
$lltstamplimit = $currentdateUTC.AddDays(- $numdays)
$lltintlimit = $lltstamplimit.ToFileTime()
$Search = "TOPLEVEL DOMAIN"
$ou = (Get-ADOrganizationalUnit -Ldapfilter '(name=*)' -searchbase $search -searchscope Onelevel | where { $_.name -like $OUN }).Distinguishedname
$users = get-aduser -filter * -searchbase "$ou" -properties * | where { $_.enabled -like "True" } | select SamAccountName, LastLogonDate
$convert = foreach ($i in $users.lastlogondate) { [datetime]::FromFileTime($i).ToString('g') }
#$array = foreach ( $i in $users ) {
#if ( $users.Lastlogondate -ge $lltintlimit ) { $recent += $i } else { $oud += $i}
As you might be able to guess the script fails at the convert part. Everything after is comment, I have not really done anything with that yet. Anyway I want to convert the output to a normal date system so I can calculate whether or not the lastlogondate is before or after the period I gave earlier.
Do you have any idea how I can fix this, or an alternative to this that might work as well?
Upvotes: 3
Views: 2400
Reputation: 993
There are some limitations to filtering AD accounts using the LastLogonDate property, mainly that LastLogOnDate is not always updated across all DCs, Technet article explains in more detail.
$inActiveUsers = Search-ADAccount -AccountInactive -TimeSpan "90" -UsersOnly
$inActiveUsers | foreach { Disable-ADAccount -Identity $_ }
The online help for the Search-ADAccount can be found here.
Upvotes: 2