Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell find users expiring in 7 days

I am trying to run a powershell script that queries for accounts that expire within 7 days, I currently have

$a = (get-date).AddDays(7) ; Search-ADAccount -AccountExpiring -TimeSpan "7" | Select-Object SamAccountName,AccountExpirationDate | Sort-Object AccountExpirationDate | Export-Csv 7_days.csv

However when I make the following change, it seems to have some trouble and I end up getting an empty CSV file. Ultimately I want account expiring in 7 days, not more, not less.

$a = (get-date).AddDays(7) ; Search-ADAccount -AccountExpiring -TimeSpan "7" | Select-Object SamAccountName,AccountExpirationDate | Sort-Object AccountExpirationDate | Where-Object {$_.AccountExpirationDate -like $a } | Export-Csv 7_days.csv

Can someone let me know what I am doing wrong? I have tried moving the "Where-Object {$_.AccountExpirationDate -like $a } " piece around, or "-match" instead of "-like" , however these havn't landed me much success. Where am I going wrong with this?

like image 462
perlnoob Avatar asked Apr 20 '12 13:04

perlnoob


1 Answers

Update: You can get the accounts if you pass a string value, passing an integer initializes the timespan to 7 ticks!

Search-ADAccount -AccountExpiring -TimeSpan "7"

other valid options:

Search-ADAccount -AccountExpiring -TimeSpan (New-TimeSpan -Days 7)
Search-ADAccount -AccountExpiring -TimeSpan ([TimeSpan]::FromDays(7))

Could be a bug, it doesn't work for me as well. Here's a workaround:

$NeverExpires = 9223372036854775807
$ExpringIn = (Get-Date).AddDays(7) 

Get-ADUser -Filter * -Properties accountExpires | 
Where-Object {$_.accountExpires -ne $NeverExpires  -and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpringIn }
like image 55
Shay Levy Avatar answered Sep 23 '22 19:09

Shay Levy