Arbelac
Arbelac

Reputation: 1902

Account expiry dates or account Never expire for all AD users

While I am running the below command getting expiration_date is blank.

Is it possible to get the 'Never expire' instead of blank in expiration_date?

Import-Module ActiveDirectory
$Groups = Get-ADGroup -filter {Name -like "SSL_VPN_Users" } | Select-Object Name
ForEach ($Group in $Groups) {
  Get-ADGroupMember -identity $($group.name) -recursive | 
    Get-ADUser -Properties samaccountname,mail,AccountExpires | 
    select samaccountname,mail,@{l="expiration_date";e={[datetime]::fromfiletime($_.accountexpires)}} | 
    Export-csv -path C:\SSLVPN\SSL_VPN_Users.csv -NoTypeInformation
}

Upvotes: 1

Views: 4913

Answers (1)

DAXaholic
DAXaholic

Reputation: 35368

The problem is probably when the account never expires the value of AccountExpires is the max. int64 value which results in an ArgumentOutOfRangeException when calling [datetime]::FromFileTime for it.

Therefore try the following - I introduced the helper function accountExpiresToString for better readability of the expression script block but you can pack the function's code directly within the script block if you prefer that.

function accountExpiresToString($accountExpires) {
    if (($_.AccountExpires -eq 0) -or 
        ($_.AccountExpires -eq [int64]::MaxValue)) {
        "Never expires"
    }
    else {
        [datetime]::fromfiletime($accountExpires)
    }
}

Import-Module ActiveDirectory
...
ForEach ($Group in $Groups) {
  Get-ADGroupMember ... | 
    Get-ADUser -Properties ...,AccountExpires | 
    Select-Object @{l="expiration_date";e={ accountExpiresToString($_.AccountExpires)}} | 
    Export-Csv ...
}

Update: If of interest, here is a page on MSDN describing that 0 and 0x7FFFFFFFFFFFFFFF ([int64]::MaxValue) indicates an account that never expires.

Upvotes: 1

Related Questions