Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

unexpected behavior using try / catch/ finally in a foreach loop

$
0
0

I have an issue with using try/catch/finally in a foreach loop.  The catch works when a server name can not be resolved and puts the unresolved name in the cantconnect array,  however, the script reruns the proceeding server name and it gets put in twice to the corresponding array.  If all the names resolve, the script works with out issue:


$serverstoberesolved = Get-Content C:\txt\serverlist.txt
$cantconnect = @()
$issuancesuccess = @()
$issunancemissing = @()

$erroractionpreference = "stop"

 # start for loop

foreach ($servers in $serverstoberesolved)
{

    Try {
        $Server = ([system.net.dns]::gethostbyname("$servers")).hostname
        }
    Catch {
      $cantconnect += $servers
      }
    Finally {

        if ((test-connection -computername $server -count 1 -quiet) -eq $true)
            {
                if ((test-path -path $path) -eq $true)
                {
                $issuancesuccess += $Server
                }
                else
                {
                $issunancemissing += $server
                }
            }
        Else
            {
            $cantconnect += $server
            }
        
        }
 } # end server loop


Viewing all articles
Browse latest Browse all 10624

Trending Articles