Blog Post

Getting a Day Difference in PowerShell–#SQLNewBlogger

,

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

SSMS froze on me the other day. Actually, it lightly responded to some things, but the window wouldn’t redraw and I couldn’t see the query window. I could see the results pane, but couldn’t get the app to respond.

I wanted to get the difference between two dates, and wasn’t sure, so I quickly searched. I tried assigning the date to a variable, but this creates a string:

$start = “2020-03-11”

With a couple searches, I learned I can use Get-Date to get a date variable. In this case, I’d do this:

$start = Get-Date -Date "2020-03-11"

If I did that with two dates, I could get the difference. Here’s a screen show that shows I get the result in a variety of different time slices.

2022-02-15 10_22_09-E__..._git_fwddemo

If I wanted just days, I could do this:

($end - $start).Days

That returns just the 712.

I also learned I could shortcut this with a TimeSpan type.

New-TimeSpan -Start “2020-03-11” -End (Get-Date)

I get the same spread of time parts as the image above, or I can enclose this all in parenthesis and then call the “Days” property to get that value.

SQL NewBlogger

I hadn’t done much with date and time in PoSh, and after seeing an article from an author, I investigated a bit more. This was a part of what I tried to do, albeit as a response to something not working as expected.

Good to know how to work with dates, as I can see this being a part of many PoSh scripts that might clean up old files or otherwise take action based on time values.

You could write this post in about 10-15 minutes and show how you use PoSh to work with date and times.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating