0

I'm trying to write a PowerShell script for my own use to run it at Windows start up, so it volume up gradually. It works well when I copy the script and paste it in the PowerShell window and click enter, but it does not work when I save the script content in the .ps1 file and Run it with PowerShell from the context menu. It is immediately closed and doesn't wait until the condition from interval is done.

$timer = New-Object Timers.Timer

$iter = 0;

$action = {
  $iter += 1;
  Write-Host "Interval: $iter";
  if ($iter -eq 10) {
    Unregister-Event thetimer;
    pause;
  }
} 
$timer.Interval = 1000  #3 seconds

Register-ObjectEvent -InputObject $timer -EventName elapsed –SourceIdentifier thetimer -Action $action

$timer.Start()

I simplified the script. What command and where should I use, to hang the script till the interval event is finished?

1 Answer 1

1

The pause command inside the timer scriptblock doesn't affect the parent process from which you're starting the timer.

To keep the parent window open until the timer finishes you could add a loop checking the job status:

...
$timer.Start()

do {
    Start-Sleep -Milliseconds 100
    $job = Get-Job -Name 'thetimer'
} while ($job.State -in 'NotStarted', 'Running')
Sign up to request clarification or add additional context in comments.

1 Comment

To keep the parent window open, I would just use Wait-Event.

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.