How to capture error details within a while loop? … in PowerShell RRS feed

  • Question

  • I have a power shell script that checks if the connection to an Ip address is live. I have added a timer to the code so it loops and checks for 4 minutes then sleeps then starts again. I have also added this script to task schedule that runs every 5 minutes.

    However my problem is the script only capture the error details if the errors occurs outside the while loop. If there is an error while the code is looping, the error variable is empty and unfortunately all the errors occur withing the loop.

    This is the code I have. Apart from the above, everything works fine. Any suggestions or answers?

    function Make_Decision() {
        if ($val -eq 0) {
            $msg = "Connection to [$IPaddress] FAILED`n"
            Add-Content -path C:\path\results.txt -value "[$date] - { $msg }"
    ## Connection Test Function
    function Test_Port_Connection() {
        $date = Get-Date -Format g
        $portNumber = 0000
        $IPaddress = ''
        $timeout = new-timespan -Minutes 4
        $sw = [diagnostics.stopwatch]::StartNew()
        ## Establishing TCP Connection
        $host_connection = New-Object System.Net.Sockets.TCPClient
        try {
            $host_connection.Connect($IPaddress, $portNumber)
        catch {
            $erro = "[$date] - $_"
            #Add-Content -path C:\path\errors.txt -value "[$date] - { $erro }"
            $erro | Out-File C:\path\errors.txt -Append
        while ($sw.elapsed -lt $timeout) {
            #while loop starts
            if (($host_connection.Connected) -and (Test-Connection -IPAddress $IPaddress -Count 1 -ErrorAction SilentlyContinue)) {
                $val = 1
            else {
                $val = 0
            start-sleep -Seconds 1
        } # end of while loop
    Thursday, March 21, 2019 2:34 PM

All replies

  • You need to use a Try/Catch block inside of the loop.

    Perhaps ask the person who wrote the script to help you.


    Thursday, March 21, 2019 6:05 PM
  • Hi,

    Was your issue resolved?

    If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.

    If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.

    If no, please reply and tell us the current situation in order to provide further help.

    Best Regards,


    Just do it.

    Wednesday, March 27, 2019 6:38 AM