Add-Type -AssemblyName System.DirectoryServices.AccountManagement $users = get-content 'users.txt' $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain foreach($username in $users){ $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username) "------" "Name: " + $user."DisplayName" "Username: " + $username "Account Active: " + $user."Enabled" "Account Expiration: " + $user."AccountExpirationDate" " " }
Here is the "users.txt" file....it is just the usernames, one per line:
U1234567 U2345678 U3456789
This gives this output:
------ Name: Smith, Joe Username: U1234567 Account Active: True Account Expiration: 01/06/2016 06:00:00 ------ Name: Smith, Bob Username: U2345678 Account Active: True Account Expiration: 01/06/2016 06:00:00 ------ Name: Smith, Billy Username: U3456789 Account Active: True Account Expiration: 01/06/2016 06:00:00Hopefully this gives you some other ideas for how to query Active Directory using PowerShell.
Thanks! This works perfectly.
ReplyDeleteHow would you go about to export the result to a text file with columns and heads like Username DisplayName etc?
Br
Niklas
This would be a pretty simple change to the script. Just move the column headings above the loop and print the fields on a single line. Something like this:
DeleteAdd-Type -AssemblyName System.DirectoryServices.AccountManagement
$users = get-content 'users.txt'
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
"Name,Username,Account Active,Account Expiration"
foreach($username in $users){
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
$user."DisplayName" + "," +
$username + "," +
$user."Enabled" + "," +
$user."AccountExpirationDate"
}