[英]Powershell continue script on Exception
I am a powershell newbie. 我是超级新手。 I wrote this little script to find the DNS entries of my server list. 我写了这个小脚本来查找服务器列表中的DNS条目。 When I run with several computernames, It is working fine without any issues. 当我使用多个计算机名运行时,它工作正常,没有任何问题。 When it handles an invalid hostname, it is being caught by the catch block but the script just terminates instead of continuing with the next hostname. 当它处理无效的主机名时,它会被catch块捕获,但是脚本只是终止而不是继续下一个主机名。 What am I doing wrong here? 我在这里做错了什么?
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
{
}
}
Your foreach
is inside the try
block, so when an exception occurs, it goes to the catch
block which is outside the loop. 您的foreach
位于try
块内,因此,当发生异常时,它将转到循环外的catch
块。 Put both the try
and the catch
inside the foreach
loop. 将try
和catch
放入foreach
循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.