Search for user in domain AD

Viewed 31

Working on this code for creating a new user script and I havent got much experience with if statements. I am trying to get the system to detect if the new user matches an already existing user and if it does, ask for the middle name.

$firstName = Read-Host -Prompt 'Please enter new users first name'

$lastName = Read-Host -Prompt 'Please enter new users last name'

$userName = "$firstName.$lastName"

if ($username -match -ADUser)
    {

    write-host "$userName is already in use"
    $Selection = read-host "Would you like to add a middle name? (Y/N)"
    switch ($Selection) {
    'Y'{
    
    $middleName = read-host - prompt "Please enter the users middle initial"
    $userName = "$firstName.$middleName.$lastName"
    
    }
    'N' {
    
    return
    
    }
    }
}
else{

}
1 Answers

I was able to figure it out. If anyone else is having the same issue, follow this. Create a variable for searching AD for the name, then match it against the user you are creating.

My code:

$firstName = Read-Host -Prompt 'Please enter new users first name'
$lastName = Read-Host -Prompt 'Please enter new users last name'

$userName = "$firstName.$lastName"
$activeSearch = Get-ADUser -Identity $userName

if ($activeSearch -match $userName)
    {

        write-host "$userName is already in use"
        $Selection = read-host "Would you like to add a middle name? (Y/N)"
        switch ($Selection) {
        'Y'{
    
            $middleName = read-host - prompt "Please enter the users middle initial"

            $userName = "$firstName.$middleName.$lastName"
    
        }
        'N'{
    
            return
    
        }
    }
}
else{

}
Related