Home > Net >  powershell AD how to check if user exist and if not then create it
powershell AD how to check if user exist and if not then create it

Time:01-06

function CreateUSR ([string]$name, [string]$path) {
$test = "OU=$name,$path"

$VerbosePreference = "Continue"

# Check if the user exists
try  {
    get-ADUser -Identity $test  | Out-Null
    Write-Verbose "OU '$test'already exists."
}

catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
    Write-Verbose "Creating new User '$test'"
    New-ADUser -name $name -Path $path
}

catch {
"An error occurred that could not be resolved."} 
}
New-ADUser -name "Flip" -path "OU=testorganization,DC=NET,DC=DSAS,DC=NL" -OtherAttributes @{'title'="director" ;'mail'="test@test"}

CodePudding user response:

instead of using get-ADUser -Identity $test | Out-Null you can use

if (!(Get-aduser -filter {samaccountname -eq $test})){
    Write-Verbose "Creating new User $test"
    New-ADUser -name $name -Path $path
} else {
    write-host "User $test already exist!"
}

CodePudding user response:

Give this a try, instead of passing a Path as parameter, it's easier to use an OU Name and search for it. I have added an if condition that considers the possibility that more than one OU with the same name can be found, I have not tested it's functionality and this should of course be improved.

function CreateUSR {
param(
    [parameter(Mandatory)]
    [string]$Name,
    [parameter(
        Mandatory,
        HelpMessage = 'Name of the OU where the user should be created.'
    )]
    [string]$OUName
)

    $ou = Get-ADOrganizationalUnit -LDAPFilter "(name=$OUName)"
    $user = Get-ADUser -LDAPFilter "(anr=$Name)"

    if(-not $ou)
    {
        throw "$OUName could not be found on this Domain."
    }
    if($ou.Count -gt 1)
    {
        @(
            "More than one OU with name $OUName was found."
            "Choose one using the Index Number!"
        ) | Write-Host -ForegroundColor Red

        $ou.foreach({
            begin { $i = 0 }
            process { "$i - {0}" -f $_.DistinguishedName; $i   }
        })

        [int]$index = Read-Host 'Index'
        $ou = $ou[$index]
    }
    if($user)
    {
        throw "$user already exists!"
    }

    New-ADUser -Name $Name -Path $ou
}
  •  Tags:  
  • Related