首页 > 解决方案 > 避免呼叫深度溢出失败

问题描述

我创建了一个脚本来测试两点之间的互联网连接,但是在〜1小时后脚本失败了

由于调用深度溢出,脚本失败。

我模糊地理解我创建的递归行为的想法,但正在寻找一种方法来让这个脚本有时运行几天而不会出现问题。

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

标签: powershellrecursion

解决方案


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
}

推荐阅读