Powershell - Check if OU exists with credential

109 Views Asked by At

I wish to create a script to automatically configure a server and join it to a domain. Before joining, I wish the user to enter a valid OU distinguished name. So I need to check if this OU exists.

Problem is, this check will be done on a server not joined to the domain (of course...), and without the possibility to install AD Powershell Module (so no Get-ADOrganizationUnit...).

So I try to use [ADSI]::exist command to check if the OU does exist

Here is where I am:

Do{
         $serverOU = read-host "Please, enter a valid Distinguished Name of the OU where to move the server in Active Directory"

         $OUcheck = [adsi]::Exists("LDAP://$serverOU")
         if ($OUcheck -ne "True"){
            write-host "This OU does not exist" -ForegroundColor Red
            }
         }

But of course, -Credential doesn't work. I saw there is a possibility to do something with the command

New-Object System.DirectoryServices.DirectoryEntry

But I don't really understand how to use that.

Is there someone who can give me a direction?

Thanks in advance,

1

There are 1 best solutions below

0
Matt On

For those who wondering, here's how I got around the problem...

I created a loop with the error code in case of problem. If there is no error while joining the domain, the script continue normally. If there is any problem, it stops. If problem with the OU distinguished name, it goes back to the line to choose the OU.

Join domain
Write-host "Joining $hostname to the domain" -ForegroundColor Green
Do{
    $serverOU = read-host "Please, enter a valid Distinguished Name of the OU where to move the server in Active Directory"
    Add-Computer -DomainName $Domain -Credential $Credential -OUpath $serverOU -Force -ErrorAction SilentlyContinue -ErrorVariable ADError
    if(!$ADError){
    write-host "server $hostame has been joined to the domain" -ForegroundColor DarkGreen
    }else{
        if($ADError -match "Access is denied"){
        Write-Host "ERROR: Access denied - Please relaunch Powershell in Administrator Mode or use an account with right to add computer to the domain" -ForegroundColor red
        pause
        exit
        }
        elseif($ADError -match "The user name or password is incorrect"){
        Write-Host "ERROR: The user name or password is incorrect - Please relaunch the script and use a valid account" -ForegroundColor red
        pause
        exit
        }
        elseif($ADError -match "The system cannot find the file specified"){
        Write-Host "ERROR: The OU doesn't exist - Please enter a valid OU Distinguished Name" -ForegroundColor Yellow
        }else{
        write-host "ERROR: Please perform all action manually or contact admin system" -ForegroundColor red
        $ADerror
        pause
        exit
        }
    }
}until(!$ADerror)