Search code examples
powershellautomationactive-directoryexport-to-csvget-aduser

Get AD account expiry date from a list of users names and output the names, usernames and expiry dates of the users to CSV


I have a command which would I would have to define the username of user and this will display the username, name and expiry date of the user:

$user = "Username of User"
get-aduser $user -property * | select samaccountname, displayname, accountexpirationdate

Which outputs:

samaccountname                                                  displayname                                                     accountexpirationdate                                         
--------------                                                  -----------                                                     ---------------------                                         
Username                                                        Name of User                                                    02/11/2023 00:00:00

I was wondering if it possible to define a list of usernames either in .txt file or CSV file and create a script to read text/csv file of each username and to pull off the username, display name and expiry date of that user to CSV file.


Solution

  • This is quite simple, just need to define an input file where you will place the identities of the users to query (one in each line) then each line can be passed through the pipeline to Get-ADUser where you define which attributes are of interest and the rest is just filtering the properties of interest with Select-Object and exporting to a CSV file with Export-Csv.

    Just note that an identity can be one of the following:

    • A distinguished name
    • A GUID (objectGUID)
    • A security identifier (objectSid)
    • A SAM account name (sAMAccountName)
    Get-Content path\to\inputfile.txt |
        Get-ADUser -Properties samaccountname, displayname, accountexpirationdate |
        Select-Object samaccountname, displayname, accountexpirationdate |
        Export-Csv path\to\exportCsv.csv -NoTypeInformation