运行环境:Windows Server 2012 R2
此powershell脚本为自动修改本机DNS并加入到域中
但有的时候会提示【本地计算机当前不是域的一部分。请重新执行脚本!】错误,如遇到该错误可按照提示重新执行脚本
若多次执行后还是报错,错误原因是脚本将本机加入到域中,但是域控中未出现本机所致
终级解决方案:退出域后手动加域,这种方式大概率在域控中能找到本机
# 自动修改本机DNS并加入到域中
# author:lttr <www.cnblogs.com/GoCircle>
# date:2019-08-09 # eg. # C:\domain.ps1 -DNS "1.1.1.1","2.2.2.2" -Domain "test.com" -UserName "admin" -Password "123" [CmdletBinding()] param ( # DNS列表,可设置两个 [Parameter(Mandatory=$true,Position=0)][string[]]$DNS, # 域名 [Parameter(Mandatory=$true,Position=1)][string]$Domain, # 域账户 [Parameter(Mandatory=$true,Position=2)][string]$UserName, # 域账户密码 [Parameter(Mandatory=$true,Position=3)][SecureString]$Password ) $wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'" #设置DNS $wmi.SetDNSServerSearchOrder($DNS)>$null # 验证DNS是否设置成功 if(($wmi.DNSServerSearchOrder | ForEach-Object{ $DNS -Match $_ }).Count -eq $DNS.Count){ write-host "DNS success" #加入域 $pwd = $Password | ConvertTo-SecureString -asPlainText -Force $credential = New-Object System.Management.Automation.PSCredential("$Domain\$UserName",$pwd) $server = (Get-WmiObject -Class Win32_ComputerSystem | Select-Object Name).Name Add-Computer -ComputerName $server -DomainName $Domain -Credential $credential -PassThru -Verbose -ErrorAction SilentlyContinue -WarningAction silentlyContinue Start-Sleep -Seconds 3 # 测试是否加入到域中 try{ if(Test-ComputerSecureChannel -Server "$server.$Domain"){ Reset-ComputerMachinePassword -Server $Domain -Credential $credential write-host success! pause Restart-Computer -Force }else{ Write-Warning "本地计算机当前不是域的一部分。请重新执行脚本!" } }catch{ Write-Warning "本地计算机当前不是域的一部分。请重新执行脚本!" } }else{ Write-Warning "DNS设置失败,请重新执行脚本!" }