Get all users from specific Organizational Unit in an Active Directory

Ever found yourself in need of collection all users in a specific OU, filter for a given set of properties and export the list to a file? If yes, this script is for you!

$Users = Get-ADUser -SearchBase "OU=Sub-OU,OU=Parent-OU,DC=domain,DC=tld" -Filter * -Properties * | Select-Object SamAccountName,DisplayName,GivenName,Surname,whenCreated,Enabled,accountExpires,lastLogonTimestamp,LockedOut
$OUUsers = @()
$OUUsers += "SamAccountName,DisplayName,GivenName,Surname,whenCreated,Enabled,accountExpires,lastLogonTimestamp,LockedOut"
foreach ($User in $Users) {
    if ($User.accountExpires  -eq "9223372036854775807") {
        $OUUsers += "$($User.SamAccountName),$($User.DisplayName),$($User.GivenName),$($User.Surname),$(($User.whenCreated).ToString('yyyy-MM-ddZhh-mm-ss')),$($User.Enabled),$("Never"),$([datetime]::FromFileTime($User.lastLogonTimestamp).ToString('yyyy-MM-ddZhh-mm-ss')),$($User.LockedOut)"
    }
    if (-not($User.accountExpires  -eq "9223372036854775807")) {
        $OUUsers += "$($User.SamAccountName),$($User.DisplayName),$($User.GivenName),$($User.Surname),$(($User.whenCreated).ToString('yyyy-MM-ddZhh-mm-ss')),$($User.Enabled),$([datetime]::FromFileTime($User.accountExpires).ToString('yyyy-MM-ddZhh-mm-ss')),$([datetime]::FromFileTime($User.lastLogonTimestamp).ToString('yyyy-MM-ddZhh-mm-ss')),$($User.LockedOut)"
    }
}
$OUUsers | Out-File C:\tmp\OUUser-Report.csv

The script will search in domain.domain.tld\Parent-OU\Sub-OU and will select all users in this sub-OU. Here, it will collect the properties SamAccountName, DisplayName, GivenName, SurName, whenCreated, Enabled, accountExpires, lastLogonTimestamp and LockedOut. These properties will then be exported to the file OUUser-Report.csv which will be stored in C:\tmp.

Leave a Reply

Your email address will not be published. Required fields are marked *