0

I created a script to test internet connection between two points, however after ~1hr the script fails with

The script failed due to call depth overflow.

I vaguely understand the idea of the recursive behavior I created, but looking for a way to allow this script to run for sometimes days without issue.

0435081769$targetAddress = 'Target-PC'
$outputDir = 'C:\Support\Logs'
$outputFile = 'NetworkStabilityLog.csv'

function Set-ConsoleWindow() {
    $pshost = Get-Host
    $pswindow = $PSHost.UI.RawUI
    $newsize = $PSWindow.WindowSize
    $newsize.Width = 50
    $newsize.Height = 15
    $PSWindow.WindowSize = $newsize
}

function Check-Dir() {
    if (!(Test-Path $outputDir\$outputFile)) {
        New-Item -ItemType Directory -Force -Path $outputDir
    }
    Add-Content $outputDir\$outputFile "Target Address, Status, Date"
    Clear
}

function Display-Message() {
    Write-Host "Testing connection to $targetAddress in progress"
    Write-Host
    Write-Host "Close window to stop test."
    Write-Host
}

function Ping-Network() {
    $date = Get-Date

    $checkIP = Test-Connection -ComputerName "$targetAddress" -Quiet -Count 1 -BufferSize 1

    if ($checkIP -Match "False") {
        Add-Content $outputDir\$outputFile "$targetAddress, Fail, $date"
        Write-Host "Connection Down at $Date"
    }

    Sleep-Script
}

function Sleep-Script() {
    Start-Sleep -Seconds 1
    Ping-Network
}

Set-ConsoleWindow
Check-Dir
Display-Message
Ping-Network
0

1 Answer 1

3

Ping-Network and Sleep-Script call each other recursively without ever breaking out of it. Of course you're getting an overflow there. Don't do that. EVER!

If you want an infinite loop: do an infinite loop. Remove the function Sleep-Script from your code and replace the last line (Ping-Network) with this:

while ($true) {
    Ping-Network
    Start-Sleep -Seconds 1
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I am still new at coding, but I don't see the difference in why it works when it is contained in one function instead of two functions calling each other.
@pmac5 When you call one function from another the state of the caller must be stored somewhere until the call returns and the calling function resumes operation. However, with your construct of 2 functions calling each other no call ever returns, so you just keep stacking function state on function state on function state. Until you reach the maximum call depth and error out.
Thanks! appreciate the explanation, makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.