Powershell find users expiring in 7 days

43,206

Solution 1

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 }

Solution 2

The attribute in use is accountExpires and is express in pacquet of 100 nano second since 1600

PS C:\Windows\system32> Get-ADuser user1 -Properties accountExpires


accountExpires    : 129821976000000000
DistinguishedName : CN=user1 users,OU=OUTest,DC=dom,DC=fr
Enabled           : True
GivenName         : user1
Name              : user1 users
ObjectClass       : user
ObjectGUID        : b1bef798-8e36-45ff-ad11-e79f89769efc
SamAccountName    : user1
SID               : S-1-5-21-3115856885-816991240-3296679909-1146
Surname           : Users
UserPrincipalName : [email protected]

you can convert it to [dateTime] like this :

PS> [datetime](Get-ADuser user1 -Properties accountExpires).accountExpires

mardi 22 mai 0412 22:00:00

Solution 3

Try the following PowerShell command

Search-ADAccount -AccountExpiring -TimeSpan 6.00:00:00 | FT Name,ObjectClass -A

https://technet.microsoft.com/en-us/library/ee617247.aspx

Share:
43,206
perlnoob
Author by

perlnoob

Updated on July 09, 2022

Comments

  • perlnoob
    perlnoob about 2 years

    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?