Skip to content

Instantly share code, notes, and snippets.

@emyann
Created June 15, 2016 04:27
Show Gist options
  • Save emyann/826d9f799fb5f0d115ac3b9eaaa3a958 to your computer and use it in GitHub Desktop.
Save emyann/826d9f799fb5f0d115ac3b9eaaa3a958 to your computer and use it in GitHub Desktop.
A Powershell random generator for dates and times
function Get-RandomDateBetween{
<#
.EXAMPLE
Get-RandomDateBetween -StartDate (Get-Date) -EndDate (Get-Date).AddDays(15)
#>
[Cmdletbinding()]
param(
[parameter(Mandatory=$True)][DateTime]$StartDate,
[parameter(Mandatory=$True)][DateTime]$EndDate
)
process{
return Get-Random -Minimum $StartDate.Ticks -Maximum $EndDate.Ticks | Get-Date -Format d
}
}
function Get-RandomTimeBetween{
<#
.EXAMPLE
Get-RandomTimeBetween -StartTime "08:30" -EndTime "16:30"
#>
[Cmdletbinding()]
param(
[parameter(Mandatory=$True)][string]$StartTime,
[parameter(Mandatory=$True)][string]$EndTime
)
begin{
$minuteTimeArray = @("00","15","30","45")
}
process{
$rangeHours = @($StartTime.Split(":")[0],$EndTime.Split(":")[0])
$hourTime = Get-Random -Minimum $rangeHours[0] -Maximum $rangeHours[1]
$minuteTime = "00"
if($hourTime -ne $rangeHours[0] -and $hourTime -ne $rangeHours[1]){
$minuteTime = Get-Random $minuteTimeArray
return "${hourTime}:${minuteTime}"
}
elseif ($hourTime -eq $rangeHours[0]) { # hour is the same as the start time so we ensure the minute time is higher
$minuteTime = $minuteTimeArray | ?{ [int]$_ -ge [int]$StartTime.Split(":")[1] } | Get-Random # Pick the next quarter
#If there is no quarter available (eg 09:50) we jump to the next hour (10:00)
return (.{If(-not $minuteTime){ "${[int]hourTime+1}:00" }else{ "${hourTime}:${minuteTime}" }})
}else { # hour is the same as the end time
#By sorting the array, 00 will be pick if no close hour quarter is found
$minuteTime = $minuteTimeArray | Sort-Object -Descending | ?{ [int]$_ -le [int]$EndTime.Split(":")[1] } | Get-Random
return "${hourTime}:${minuteTime}"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment