Friday Fun: Timing is Everything

For today’s fun I want to introduce you to a PowerShell project I’ve been working on. As with many of these Friday Fun projects this is something that is hardly groundbreaking but it could be fun to use and hopefully serves an educational purpose.  What I have is a module called MyTimer that contains several commands designed to work with a very simple timer. In fact it is so simple you’ll probably think I’m joking.

The commands are based on an extremely simple principal: how much time has elapsed between two events? You can easily do this now with New-Timespan or simply subtracting one datetime from another. My module takes the simplest approach possible: save the current date and time to a variable and when you are ready, calculate a timespan from that variable. Even though the commands reference a “timer” object there really isn’t anything fancy or complicated. It is simply a variable that you can name, that has a datetime value.

There’s no .NET magic or anything complicated. The module commands are designed to make it easier to manage all of this. You can even create multiple timers at the same time in case you want to stop them at different intervals.

If you forget what names you’ve given your timers, which I did, you can use the Find-MyTimer command.

Find my PowerShell timer variables

When you are ready to stop a timer, I bet you can guess what command to use.

Stopping a timer

All the command did was find the variable and calculate a timespan. To make things easy I even added a parameter to get the value as a string.

Getting time result as a string

When you stop a timer, the original variable is removed.

Finally, I also included a command called Get-MyTimer which will show you the current elapsed time, but doesn’t “stop” it. This works nicely with Find-MyTimer.

Getting the current state of the "timer"

Because this is so simple you get your prompt back immediately and it doesn’t interfere with the rest of your work. Say you get a phone call from an annoying co-worker. You can kick off a timer and when you hang up 90 minutes later you can stop the timer and record exactly how long you were occupied.

Another option is that you could export your timer variables to a file and in a later PowerShell session re-import them. This could be handy when tracking something that might last for days.  In fact, I may have to think about this as an enhancement.

The module is available now on GitHub at https://github.com/jdhitsolutions/MyTimer. I’d love for you to try it out and let me know what you think. Post bugs or requests on GitHub. Eventually I’ll probably publish this to the PowerShell Gallery.

But for now, have fun and enjoy!