windows - 在 Windows PowerShell 中使用计时器
问题描述
我试图弄清楚如何在 Windows PowerShell 中使用计时器。我希望我的脚本在一定时间内运行命令/任务,停止任务,然后将结果输出到 txt 文件。这是我到目前为止所拥有的:
$timer = [Diagnostics.Stopwatch]::StartNew()
while ($timer.elapsed.totalseconds -lt 10){
netstat 169.254.219.44
$timer.stop() |
Out-File $PSScriptroot\connections.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 $PSScriptroot\connections.txt -Append
netstat 169.254.219.44 | Out-File $PSScriptroot\connections.txt -Append
}
$timer.stop()
推荐阅读
- c# - 我怎样才能改进我的人工智能不来回反弹
- c++ - 无法使用 openCV 读取内存 MFC C++
- iot-devkit - 如何重置 MXChip Azure IoT DevKit 以停止编程 LED 闪烁
- php - MySQL 结果到 PHP 数组
- python - 如何“投射” python 类型提示
- angular - Angular 2 - 将对象从父组件传递到子组件以进行修改
- javascript - 检查夏令时时刻js
- android - 无法解决:com.google.firebase:firebase-core:16.0.1 - 只有 1 build.gradle
- python - 从 sqlite 迁移到 postgres (django) 时如何更新单元测试
- database - 维度模型中的事实表实际上是事件表吗?