Powershell继续在Exception上编写脚本

时间:2015-01-05 22:42:06

标签: powershell powershell-v3.0

我是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
{
}
}

1 个答案:

答案 0 :(得分:2)

您的foreach位于try块内,因此当发生异常时,它将转到循环外的catch块。将trycatch放在foreach循环中。