powershell - 避免呼叫深度溢出失败
问题描述
我创建了一个脚本来测试两点之间的互联网连接,但是在〜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
解决方案
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
}
推荐阅读
- php - 使用 PDO/PHP 从一个存储过程中获取 2 个不同的结果
- python - Tensorflow:尝试通过张量值访问变量的索引?
- r - 在多个解释变量的数据框中回归多个因变量的数据框
- .htaccess - htaccess 使用 GET 使用参数重写
- mysql - MySQL:删除大于其他字段的字段
- visual-studio-code - vscode 格式保存单行
- ios - 如何初始化和自定义 GMSPlace 对象
- c# - EF6 干扰嵌套类构造函数,不允许与静态类交互
- jquery - Ajax提交表单而不重新加载页面不起作用
- python-3.x - 函数默认参数的 Python 无效语法错误