我希望创建一个脚本来自动配置服务器并将其加入域。 在加入之前,我希望用户输入有效的 OU 可分辨名称。所以我需要检查这个 OU 是否存在。
问题是,此检查将在未加入域的服务器上完成(当然...),并且无法安装 AD Powershell 模块(因此没有 Get-ADOrganizationUnit...)。
所以我尝试使用 [ADSI]::exist 命令来检查 OU 是否存在
这就是我现在的位置:
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
}
}
但是当然,-Credential 不起作用。 我看到可以使用该命令执行某些操作
New-Object System.DirectoryServices.DirectoryEntry
但我不太明白如何使用它。
有人可以给我指点吗
提前致谢,
对于那些想知道的人,这就是我解决这个问题的方法......
我创建了一个带有错误代码的循环,以防出现问题。如果加入域时没有错误,脚本将正常继续。 如果有任何问题,它就会停止。如果 OU 专有名称有问题,则会返回到选择 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)