Powershell Active Directory Searcher Boiler Plate

I’m sure I’ll be using this more and more in the coming months as I familiarize myself with Powershell. Below is a template or boilerplate for Active Directory Searcher in Powershell. This was taken from a great video podcast from Youtube by David Hoelzer. Below is the video from Youtube. You can check out his channel for some other great videos.

Here’s the Powershell code.

$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher
$ADSearch.SearchRoot = "LDAP://$Domain"
$ADSearch.SearchScope = "subtree"
$ADSearch.PageSize = 100
$ADSearch.Filter = "(objectClass=user)"
$ADSearch.PropertiesToLoad.Add("distinguishedName")
$ADSearch.PropertiesToLoad.Add("sAMAccountName")
$ADSearch.PropertiesToLoad.Add("lastLogonTimestamp")
$userObjects = $ADSearch.FindAll()
foreach ($user in $userObjects)
{
    $dn = $user.Properties.Item("distinguishedName")
    $sam = $user.Properties.Item("sAMAccountName")
    $logon = $user.Properties.Item("lastLogonTimeStamp")
    if($logon.count -eq 0)
    {
        $lastLogon = "Never"
    }
    else
    {
        $lastLogon = [DateTime]$logon[0]
        $lastLogon = $lastLogon.AddYears(1600)
    }
    """$dn"",$sam,$lastLogon"
}

Leave a Reply

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