Update: 4/11/2022: An individual by the name of Adam Cook has taken the premise of this script and transformed it into a far more robust PowerShell module and published it on Github. I wanted to ensure I gave his project all the visibility I could. The Github page is available here:
https://github.com/codaamok/PSBusinessTime
Thanks Adam!
Have you ever needed to calculate how many business hours / working hours have elapsed between a specific date and now? For example, you may have some metric that says something needs to happen within 4 business hours. We define business hours in this case as 8AM to 5PM Monday to Friday and does not include statutory holidays. How might you go about doing that?
I found myself in this situation and figured it would be common and spent far too much time Googling trying to find someone else who built a solution for this problem. To my surprise, I was unable to find a single working example for PowerShell. Lots of examples for other languages such as T-SQL but nothing for PowerShell. I was therefore forced to solve this myself.
Hopefully this will help you if you ever find yourself in a similar situation.
Before we get into the code, I’d like to start with a quick demo. In my situation, we have a ticketing system and we want to kick off a process any time a ticket remains untouched for more than 4 business hours so we need to determine how many business hours have elapsed since the last touchpoint on the ticket.
In our example, the last time the ticket was interacted with was on December 21st, 2018 at 14:43:11. The current date in this example is Friday January 4th, 2019 at 13:41:56.
As we see in the screenshot below, after the ticket was last touched, 2 hours 16 minutes and 49 seconds elapsed until the end of that business day. Since this was a Friday the next 2 days were Saturday and Sunday and so we don’t add up these times. The next week is actually the Christmas break so we also don’t want to count any of these.
The first official day back is Wednesday January 2nd, 2019. Since the current time is newer than this we can simply add in a full 8 hours. We do the same for the 3rd. Finally on the 4th, since the current time is 1:41PM, that means we have already elapsed an additional 5 hours 41 minutes since 8AM.