Creating a timer event in Powershell

Recently I needed a timer to monitor something so I did a quick google search which to my surprise didn’t come up with much. Perhaps because this isn’t too hard, but still, I thought I would post a little something on how to do this.

If you are the developer type person then you might want to take a look at this article on the different .NET timer classes. A good read and good to know but not really needed for this post.

The timer class I’ll be using is the System.Timers.Timer  (Which can be shortened to Timers.Timer because powershell assumes the system. namespace )

$timer = new-object timers.timer

$action = {write-host "Timer Elapse Event: $(get-date -Format ‘HH:mm:ss’)"}

$timer.Interval = 3000 #3 seconds 

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


#to stop run
Unregister-Event thetimer

You’ll notice it will start to spit out the Timer Elapsed Event notices, which is all well and good, but doesn’t do much for us.


In my case I have a background process going that has an event that I’ve registered for, but, I’ve found a problem with it (a post to come on that) so I need a timer to monitor this object. Lets say my background job sets a variable, $complete, to 1 when its done. We can monitor that variable building off of the pervious code.

$complete = 0
$action = {
write-host "complete: $complete"
if($complete -eq 1)
     write-host "completed"
     Unregister-Event thetimer

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


#to stop
$complete = 1

Once we change the $complete variable to 1 and the timer goes off it checks that, finds that it should stop and cleans itself up.




About jrich

I am the Solutions Architect for Apex Learning in Seattle WA. I've been working with computers since I was 13. Started programming when I was 14. Had my first IT job as tech support at an ISP at the age of 15 and became a network admin at the age of 17. Since then I've worked at a variety of small to mid size companies supporting, maintaining and developing all aspects of IT. Mostly working with Windows based networks but have recently been working with Solaris system as well. I created this blog mostly as a place for me to take my own notes, but also share things that I had a hard time finding the info for.

Posted on June 13, 2011, in WMF (Powershell/WinRM) and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: