Search code examples
powershellactive-directoryazure-active-directoryactive-directory-group

Checking if Active Directory username exists using following conditions


$lastname = "xyz"
$firstname = "abc"

$username = $lastname_$firstname -or $firstname.$lastname #error

In this line how to check these conditions?

$aduser = get-aduser -f samaccountname -eq $username
if($true){
    write-host "username exist"
}
else{
     write-host "user doesn't exist"
}

Solution

  • If you're just trying to check if a username exists or not, then you would test whether $aduser is not $null.

    You also need to specify sAMAccountName -eq for each condition that might be met. And you also need quotes around the filter.

    $lastname = "xyz"
    $firstname = "abc"
    
    $aduser = Get-ADUser -f "sAMAccountName -eq '$($lastname)_$firstname' -or sAMAccountName -eq '$firstname.$lastname'"
    if ($aduser -ne $null) {
        Write-Host "username exist"
    } else {
        Write-Host "user doesn't exist"
    }