$inventory = Import-Csv "E:\MonitoringScripts\HealthCheck\PatStat_Pshell\inventory.csv"
foreach ($line in $inventory) {
$server_name = $($line.servername)
$port_number = $($line.port)
$resolved_true = [System.Net.Dns]::GetHostAddresses("$server_name")
#Write-Host $resolved_true
if ($resolved_true) {
#Write-Host $server_name
Write-Host 'the host is resolving'
} else {
Write-Host 'Not found in DNS'
}
}
在上面的代码中,当清单文件中有主机无法解析dns时,如何避免以下内容出现在命令promt中?
Exception calling "GetHostAddresses" with "1" argument(s): "No such host is known" At E:\MonitoringScripts\HealthCheck\PatStat_Pshell\patrol.ps1:9 char:2 + $resolved_true = [System.Net.Dns]::GetHostAddresses("$server_name") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SocketException Not found in DNS the host is resolving
我只想看看:
Not found in DNS
或
the host is resolving
答案 0 :(得分:0)
测试连接以查看主机是否首先存在。当然,现有的主机与在DNS中找到它并不完全相同。
$inventory = import-csv “E:\MonitoringScripts\HealthCheck\PatStat_Pshell\inventory.csv”
ForEach ($line in $inventory)
{
$server_name = $($line.servername)
$port_number = $($line.port)
$resolved_true = $null
if (Test-Connection -ComputerName $server_name -ErrorAction SilentlyContinue) {
$resolved_true = [System.Net.Dns]::GetHostAddresses("$server_name")
}
#Write-host $resolved_true
if($resolved_true) {
#write-host $server_name
Write-Host 'the host is resolving'
} else {
Write-Host 'Not found in DNS'
}
}
答案 1 :(得分:0)
捕获异常:
try {
[Net.Dns]::GetHostAddresses($server_name)
Write-Host 'the host is resolving'
} catch {
Write-Host 'Not found in DNS'
}
答案 2 :(得分:0)
使用Try,Catch和Final块来响应或处理终止 脚本中的错误。
您可以按以下方式应用它:
try {
$resolved_true = [System.Net.Dns]::GetHostAddresses($server_name)
} catch {
$resolved_true = $null
}
答案 3 :(得分:0)
$inventory = import-csv “E:\MonitoringScripts\HealthCheck\PatStat_Pshell\inventory.csv”
ForEach ($line in $inventory)
{
$server_name = $($line.servername)
$port_number = $($line.port)
$resolved_true = $null
try {
$resolved_true = [System.Net.Dns]::GetHostAddresses($server_name)
} catch {
$resolved_true = $null
}
#Write-host $resolved_true
if($resolved_true) {
#write-host $server_name
Write-Host 'the host is resolving'
} else {
Write-Host 'Not found in DNS'
}
}
这对我有用,非常感谢您的帮助。 我必须标记@JosefZ答案,但真的谢谢大家。