Generate Random Dates in PowerShell

You ever read something right when you actually needed it? Like, there couldn’t have been a better time in the world, and all of a sudden you see it and you say something totally cool like, “Booyah! That’s what I’m talking about baby!” Well, that’s what happened to me yesterday.

The setup : Working on a project that required (for testing purposes) a sinful amount of files. So a single directory that contained well over 50,000 files. The test required the files’ last write time to be sparsely dated, but the sample set I was working were within 3 days each other. I figured that at some point I would try out PowerShell to solve this task but was clueless on the “random” functionality that it may or may not expose. I figured if I couldn’t figure it out within like 20 minutes in PowerShell I would have to write a quick little C# app or something to get the job done. But come on… this is the type of thing that PowerShell is made for not a compiled language!

The moment: I was catching up on some favorite PowerShell blogs, when suddenly I ran across the post by the $cript Fanatic (Shay@Israel). It was like being struck by lightning and I immediately dropped everything to test out his thoughts on generating random dates within PowerShell.

The attempt: Within the first few minutes I was weary because he referred to this working in CTP2. I’m still on version 1 but I was determined to see if there was a way. Unfortunately I had a huge truck of failure dumped on me because my version of Get-Random (which I still don’t know if it’s part of version 1, or pscx) could only handle Int32 bound to the min/max parameters. DateTime.Ticks property is Int64. So I decided to post a comment to Shay asking if he had any ideas. He responded within no time and I decided to kick around his findings.

The result: We ended up with was one that could actually work on any version of PowerShell. Bonus! Anyway the following will generate a random date between the first of this year and now:

[DateTime]$theMin = "1/1/2008"
[DateTime]$theMax = [DateTime]::Now

$theRandomGen = new-object random
$theRandomTicks = [Convert]::ToInt64( ($theMax.ticks * 1.0 - $theMin.Ticks * 1.0 ) * $theRandomGen.NextDouble() + $theMin.Ticks * 1.0 )
new-object DateTime($theRandomTicks)

Pretty darn sweet! Super helpful? Maybe not for most everyone, but for my little world it was very helpful. Plus it provided for a little learning which is always a joy.

-

If you enjoyed this post and get the urge to read more in the future, please feel free to subscribe via rss.

~ by Scott Saad on June 12, 2008.

One Response to “Generate Random Dates in PowerShell”

  1. [...] [...]

Leave a Reply