Question

I'm trying to create a script that creates a unique user I Active Directory.

Before the script can create a user it needs to make sure the username is available by asking two different domains if the generated username exists. The problem is I don't how generate a new username or rerun part of the script if necessary. Lets say that if the generated username exists in one of the domains I wan't to generate a new username and try again with the new one. This is what I have so far.

Import-Module ActiveDirectory

$firstname = "Test"
$lastname = "Tester"

$SecondaryDomain = "server1.domain1.net"
$PrimaryDomain = "server2.domain2.net"
$ErrorActionPreference = "SilentlyContinue"

$Generate = [Char[]]"$firstname$lastname"
$Generatedusername = ($Generate | Get-random -Count 3) -join ""
Write-host $Generatedusername

        if (Get-ADUser -Filter {SamAccountName -eq $Generatedusername} -Server $PrimaryDomain)
            {
            #If the variable equals 1 the user exists
                $PrimaryDomainOK = "1"
            }
            else
            {
                $PrimaryDomainOK = "0"
            }




        if (Get-ADUser -Filter {SamAccountName -eq $Generatedusername} -Server $SecondaryDomain)
            {
            #If the variable equals 1 the user exists
                $SecondaryDomainOK = "1"
            }
            else
            {
                $SecondaryDomainOK = "0"
            }


Write-host "Primary Domain $PrimaryDomainOK"
Write-host "Secondary Domain $SecondaryDomainOK"


If ($PrimaryDomainOK -and $SecondaryDomainOK -eq 0)
{
Write-host "Creating Account"
}
Else
{
Write-host "Can't create account"
}
Was it helpful?

Solution

Add a while statement embracing your generation/verification which checks for the status of $PrimaryDomainOK and $SecondaryDomainOK.

...
$Generate = [Char[]]"$firstname$lastname"
while(($PrimaryDomainOK -ne 0) -and ($SecondaryDomainOK -ne 0)) {
    $Generatedusername = ($Generate | Get-random -Count 3) -join ""
    Write-host $Generatedusername
    ...        
    ...
    ...
    If ($PrimaryDomainOK -and $SecondaryDomainOK -eq 0)
    {
    Write-host "Creating Account"
    }
    Else
    {
    Write-host "Can't create account"
    }

}

Remember the closing brace.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top