在Windows PowerShell中使用计时器



我想弄清楚如何在Windows PowerShell中使用计时器。我希望我的脚本运行命令/任务一段时间,停止任务,然后将结果输出到一个txt文件。以下是目前为止的内容:

$timer = [Diagnostics.Stopwatch]::StartNew()
while ($timer.elapsed.totalseconds -lt 10){
netstat 169.254.219.44 
$timer.stop() | 
Out-File $PSScriptrootconnections.txt
break
}

脚本所做的就是在终端中运行命令,直到我按下ctrl+c。一旦我按下ctrl+c,它就停止,然后输出.txt文件。但是。txt文件是空白的。我花了太多时间想弄明白这件事。我是Windows PowerShell的新手,只是想看看我能做些什么。这个脚本没有真正的目的。我简直要疯了,我想不明白这个……

您是否希望测试连续重复直到允许的时间过去?只要条件($timer.elapsed.totalseconds -lt 10)为真,while{}块中的任何代码都将重复。正如李所说,不要停止循环中的计时器。

$timer = [Diagnostics.Stopwatch]::StartNew()
while ($timer.elapsed.totalseconds -lt 10) {
# Code in here will repeat until 10 seconds has elapsed
# If the netstat command does not finish before 10 seconds then this code will 
# only run once
# Maybe separate each netstat output in the file with date/time
"*** " + (Get-Date) + " ***" | Out-File $PSScriptrootconnections.txt -Append
netstat 169.254.219.44 | Out-File $PSScriptrootconnections.txt -Append
}
$timer.stop() 

最新更新