How to add task in cron
March 26, 2018
How to run commands remotely on ec2 instances
April 1, 2018

Active Directory : How to test if the user is present

When we create the new Active Directory we add the user to it, right? No brainer.

So, when we want to achieve this via automation say PowerShell script, it’s almost straightforward to add or create a new user in Active Directory.

But how to check programmatically if the use is added correctly or not? OR in another scenario, if want to check if the particular user is present in Active Directory or not?

So below PowerShell does the same job.





try {

    Start-Transcript -Path C:\TestADUser.log -Append
    $elapsedMinutes = 0.0
    $startTime = Get-Date
    $userFound = $false

    if (-not $Wait) {
        $TimeoutMinutes = 0
        $IntervalMinutes = 0

    if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {
        Install-WindowsFeature RSAT-AD-PowerShell

    do {
        if (Get-ADUser -Filter {sAMAccountName -eq $Username}){
            $userFound = $true

        Start-Sleep -Seconds $($IntervalMinutes * 60)
        $elapsedMinutes = ($(Get-Date) - $startTime).TotalMinutes

    } while (($elapsedMinutes -lt $TimeoutMinutes))

    if (-not $userFound) {
        if ($Wait) {
            throw "User not found within the timeout period of $TimeoutMinutes minutes."
        } else {
            throw "User was not found."
catch {
    $error[0]|format-list -force  #print more detail reason for failure