How to test if the user is present in Active Directory via PowerShell

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

How to test if the user is present in Active Directory via PowerShell

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 prommaticaly 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.

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [string]$Username,

    [Parameter(Mandatory=$false)]
    [switch]$Wait,

    [Parameter(Mandatory=$false)]
    [int]$TimeoutMinutes=15,

    [Parameter(Mandatory=$false)]
    [int]$IntervalMinutes=1
)

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
            break
        }

        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
}

2 Comments

  1. Clevrweb Services says:

    Liked it

  2. postanote says:

    Ooook, that’s a lot of code to just check if a user is there vs just doing: Get-ADUser -Identity Administrator. As for AD cmdlets, to accomplish this use case, tere is no need to install them using these approaches — technet.microsoft.com/en-us/library/ff720181.aspx’ — ‘itprotoday.com/management-mobility/powershell-implicit-remoting-never-install-module-again’

Bitnami