1

I'm trying to figure out how to use a timer in Windows PowerShell. I want my script to run a command/task for a certain amount of time, stop the task, and then output the results to a txt file. Here is what I have so far:

$timer = [Diagnostics.Stopwatch]::StartNew()

while ($timer.elapsed.totalseconds -lt 10){

netstat 169.254.219.44 

$timer.stop() | 
Out-File $PSScriptroot\connections.txt

break
}

All the script does is run the command in the terminal until I press ctrl+c. Once I press ctrl+c it stops and then outputs the .txt file. But the .txt file is blank. I've spent way more time than I should've trying to figure this out. I'm new to Windows PowerShell and was just messing around to see what I could do. There's no real purpose for this script. It's just driving me nuts that I can't figure this out...

1
  • 2
    you are STOPPING the timer inside your while loop. that means your test will never trigger. [grin] Commented Feb 28, 2021 at 1:36

1 Answer 1

7

Are you looking to have the test repeat continuously until the allowed time elapses? Whatever code is in your while {} block will repeat as long as the condition ($timer.elapsed.totalseconds -lt 10) is true. As Lee mentioned, don't stop the timer in your loop.

$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() 
Sign up to request clarification or add additional context in comments.

1 Comment

Wow I can't believe I didn't notice that... Thank you for your answers. That helps a lot and it makes sense now. I just wanted it to run netstat for a set amount of time and show me the results in a .txt file. This should accomplish that now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.