I would like to get the actual date of accounts that have expired but still enabled in the active directory. I always get the date 1 day. For example, if a user is expired today (15/11/2022), it will shows (16/11/2022)... Can you help me with this?
Get-ADUser -Filter * -properties AccountExpirationDate |
Where-Object{$_.AccountExpirationDate -lt (Get-Date) -and $_.AccountExpirationDate -ne $null -and $_.Enabled -eq $True} |
select-object Name, SamAccountName, AccountExpirationDate | Sort-Object -Property {$_.AccountExpirationDate} -Descending
CodePudding user response:
I always like to include LDAP property accountExpires
in there (PowerShell conveniently converts this to local time in Property AccountExpirationDate
)
to first check if the attribute has never been set (value 0) or if the attribute for the user has been set to 'Never Expires' (value 9223372036854775807).
Try
$refDate = (Get-Date).Date # set to midnight
# or use -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)"
Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |
Where-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and
($_.AccountExpirationDate -le $refDate)} |
Select-Object Name, SamAccountName, AccountExpirationDate |
Sort-Object AccountExpirationDate -Descending
CodePudding user response:
Thanks Theo, ive found what i was looking for
Get-ADUser -Filter 'Enabled -eq $true' -Properties AccountExpirationDate, accountExpires |
Where-Object {($_.accountExpires -gt 0 -and $_.accountExpires -ne 9223372036854775807) -and
($_.AccountExpirationDate -le $refDate)} |
Select-Object Name, SamAccountName, @{Name="AccountExpirationDate";Expression={(get-date $_.AccountExpirationDate).AddDays(-1)}} |
Sort-Object AccountExpirationDate -Descending