簡體   English   中英

在 Windows PowerShell 中使用定時器

[英]Using timers in Windows PowerShell

我試圖弄清楚如何在 Windows PowerShell 中使用計時器。 我希望我的腳本在一定時間內運行命令/任務,停止任務,然后將結果 output 保存到 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() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM