Using Get-AdUser Cmdlet with Select-object cmtlet
Use the Get-AdUser
with Select-object to get the ad user account expiration date in PowerShell.
1 2 3 |
Get-ADUser -Identity "JohnDoe" -Properties AccountExpirationDate | Select-Object AccountExpirationDate |
1 2 3 4 5 6 |
AccountExpirationDate --------------------- 7/1/2022 12:00:00 AM |
Here, the PowerShell cmdlet Get-ADUser
was used to retrieve the information about the users of the Active Directory as it is a centralized system. Now, what is Active Directory? Microsoft provides directory services named Active Directory. Active Directory is primarily used in window-based networks to help manage the network.
Active Directory also enables administrators to assign policies to users and computers and to delegate administrative tasks to other users.
In the above code, we used the following:
- The
Get-ADUser
cmdlet to retrieve the user account information - The
-Identity
parameter mentions the user account. - The
-Properties
parameter specifies that retrieve theAccountExpirationDate
property for the user account. - Finally, the
Select-Object
cmdlet displays only theAccountExpirationDate
property for the user account.
The above output displays the expiration date in the format MM/DD/YYYY HH:MM:SS AM/PM
. This provides the information on which specific date and time the account will expire (if it has been set to expire).
We can also get the expiration date without using the Select-Object
cmdlet. Instead, the information is passed to a variable $expirationDate
, which can be displayed using if-else
.
1 2 3 4 5 6 7 8 9 |
$expirationDate = (Get-ADUser -Identity "JohnDoe" -Properties "AccountExpirationDate").AccountExpirationDate if ($expirationDate){ Write-Host "Expiration Date: $expirationDate" } else{ Write-Host "The account does not have an expiration date." } |
1 2 3 |
Expiration Date: 7/1/2022 12:00:00 AM |
Suppose the account $expirationDate
variable is not empty (meaning the account has an expiration date set). In that case, the message in the if
statement saying Expiration Date: $expirationDate
is displayed along with the expiration date.
On the other hand, if the variable is empty, a message indicating that The account does not have an expiration date
would be displayed. To display these messages, we used the Write-Host
cmdlet.
This approach is helpful if one needs to perform different actions based on whether the account has an expiration date.
Read also: Get ad User description in PowerShell.
That’s all about how to get ad user account expiration date in PowerShell.