检查dns服务器是否可用

#%windir%\system32\WindowsPowerShell\v1.0\powershell.exe D:\PSScript\ERP_Production_Script\ERPRF_UpdateCheck.ps1
############脚本功能说明-2014-10-21############
#该脚本用来判断当前的DNS服务器是否可用,如果第一个DNS服务器可用,则脚本结束,否则将继续判断其他DNS服务器是否可用,最终将可用DNS服务器设置为第一个
###############################################

#####脚本开始######
#定义用于判断的域名
$dname = "www.baidu.com"
#$dname = "chkdns.idc4"

#根据是否配置网关查找使用中网卡
$index = (gwmi Win32_NetworkAdapterConfiguration |?{ $_.DefaultIPGateway -ne $null}).Index
$dnss = (gwmi Win32_NetworkAdapterConfiguration -filter "index = $index").DNSServerSearchOrder
$ConnectionID = (gwmi win32_networkadapter -filter "index = $index").NetConnectionID
#初始化用于存储DNS服务器列表的临时对象
$dnslists_new = $null
$dnslists_new = @()

#如果第一个DNS服务器可用,则脚本中断执行
$nsresult = nslookup.exe $dname $dnss[0]
If (!([string]::concat($nsresult)).contains("request timed out"))
{break}
Else {
#记录第一个不可用DNS服务器IP到临时对象
$dnslist=""|select IP,Status
$dnslist.IP = $dnss[0]
$dnslist.Status = "Error"
$dnslists_new +=$dnslist
#判断剩余的DNS服务器IP是否可用,并将其记录到临时对象
foreach ($dns in $dnss[1..$dnss.count])
{
If ($dns -ne $null)
{
$nsresult = nslookup.exe $dname $dns
#[string]::concat($nsresult)
If (!([string]::concat($nsresult)).contains("request timed out"))
{
$dnslist=""|select IP,Status
$dnslist.IP = $dns
$dnslist.Status = "OK"
$dnslists_new +=$dnslist
}
Else {
$dnslist=""|select IP,Status
$dnslist.IP = $dns
$dnslist.Status = "Error"
$dnslists_new +=$dnslist
}
}
}
#$dnslists_new
#判断当前系统是2003(5),还是2008,在设置DNS服务器的时候所使用的命令不同
If ((gwmi win32_operatingsystem).version.split(".")[0] -eq 5)
{
#查找可用的DNS服务器列表
[array]$dnslists_ok = $dnslists_new |? {$_.Status -eq "OK"}
If ($dnslists_ok -ne $null)
{
$dnsserver0 = $dnslists_ok[0].IP
netsh.exe interface ip set dns "$ConnectionID" static $dnsserver0 primary
$dnslists_ok[1..$dnslists_ok.count] | % { netsh.exe interface ip add dns "$ConnectionID" $_.IP }
}
#查找不可用的DNS服务器列表
$dnslists_new |? {$_.Status -ne "OK"} | % { netsh.exe interface ip add dns "$ConnectionID" $_.IP }
}
Else
{
#查找可用的DNS服务器列表
[array]$dnslists_ok = $dnslists_new |? {$_.Status -eq "OK"}
If ($dnslists_ok -ne $null)
{
$dnsserver0 = $dnslists_ok[0].IP
netsh.exe interface ip set dnsservers "$ConnectionID" static $dnsserver0 primary validate=no
$dnslists_ok[1..$dnslists_ok.count] | % { netsh.exe interface ip add dnsservers "$ConnectionID" $_.IP validate=no }
}
#查找不可用的DNS服务器列表
$dnslists_new |? {$_.Status -ne "OK"} | % { netsh.exe interface ip add dnsservers "$ConnectionID" $_.IP validate=no }
}


}

#查看当前的DNS服务器列表
#$dnss=gwmi win32_networkadapter -filter "NetConnectionStatus = 2"|foreach {(gwmi Win32_NetworkAdapterConfiguration -filter "index = $($_.index)").DNSServerSearchOrder}
#$dnss

 

posted on 2014-10-17 21:41  momingliu11  阅读(1442)  评论(0编辑  收藏  举报