I am a powershell newbie. I wrote this little script to find the DNS entries of my server list. 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. 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. Put both the try
and the catch
inside the foreach
loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.