我是powershell新手。我写了这个小脚本来查找我的服务器列表的DNS条目。当我运行几个计算机名称时,它运行正常,没有任何问题。当它处理无效的主机名时,它会被catch块捕获,但脚本只是终止而不是继续使用下一个主机名。我在这里做错了什么?
function Resolve-Hostname
{
[CmdletBinding()]
Param
(
# One or more compternames
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]$Computername
)
Begin
{
$dns = Get-WmiObject win32_networkadapterconfiguration | Where-Object {$_.DNSHostname -ne $null} | Select-Object DNS
Write-verbose "DNS suffix order used -"
$DNSDomainSuffixSearchOrder = $dns | Select-Object DNSDomainSuffixSearchOrder
Write-Verbose ( $DNSDomainSuffixSearchOrder | ft -AutoSize | Out-String )
Write-Verbose "DNS Servers order used -"
$DNSServerSearchOrder = $dns | Select-Object -ExpandProperty DNSServerSearchOrder
Write-Verbose ($DNSServerSearchOrder | Out-String )
}
Process
{
try
{
foreach ($computer in $Computername)
{
$dnsreport = [System.Net.Dns]::Resolve("$computer")
$dns = [pscustomobject]@{
Hostname = $computer
DNS_Suffix = $dnsreport.HostName.Split('.',2)[1]
DNSHostname = $dnsreport.HostName
IPAddress = $dnsreport.AddressList.ipaddresstostring -join ", "
Alias = $dnsreport.Aliases
}
$dns
}
}
catch
{
$dns = [pscustomobject]@{
Hostname = $computer
DNS_Suffix = '-'
DNSHostname = '-'
IPAddress = '-'
Alias = '-'
}
$dns
}
}
End
{
}
}
答案 0 :(得分:2)
您的foreach
位于try
块内,因此当发生异常时,它将转到循环外的catch
块。将try
和catch
放在foreach
循环中。