Skip to content

Instantly share code, notes, and snippets.

@thedavecarroll
Created August 10, 2022 08:11
Show Gist options
  • Save thedavecarroll/cffaddb13d6335f43c080eb78a6129df to your computer and use it in GitHub Desktop.
Save thedavecarroll/cffaddb13d6335f43c080eb78a6129df to your computer and use it in GitHub Desktop.
Simple function to add timespan
function Add-TimeSpan {
[CmdLetBinding(DefaultParameterSetName='TimeSpan')]
param(
[Parameter()]
[datetime]$Timestamp = (Get-Date),
[Parameter(Mandatory,ParameterSetName='TimeSpan')]
[timespan]$TimeSpan,
[Parameter(ParameterSetName='TimeSlice')]
[int]$Days,
[Parameter(ParameterSetName='TimeSlice')]
[int]$Hours,
[Parameter(ParameterSetName='TimeSlice')]
[int]$Minutes,
[Parameter(ParameterSetName='TimeSlice')]
[int]$Seconds
)
if ($PSCmdlet.ParameterSetName -eq 'TimeSlice') {
$TimeSpanParam = @{}
if ($Days -gt 0) {
$TimeSpanParam.Add('Days',$Days)
}
if ($Hours -gt 0) {
$TimeSpanParam.Add('Hours',$Hours)
}
if ($Minutes -gt 0) {
$TimeSpanParam.Add('Minutes',$Minutes)
}
if ($Seconds -gt 0) {
$TimeSpanParam.Add('Seconds',$Seconds)
}
$TimeSpan = New-TimeSpan @TimeSpanParam
}
$Timestamp + $TimeSpan
}

Usage

Dot-source the Add-TimeSpan.sp1 file or add the contents to your $PROFILE.

Add-TimeSpan -Minutes 5

Wednesday, August 10, 2022 3:11:07 AM

Add-TimeSpan -Timestamp '01/01/2022 7:45 PM' -Days 15

Sunday, January 16, 2022 7:45:00 PM

Add-TimeSpan -TimeSpan (New-TimeSpan -Minutes 5 -Hours 10 -Seconds 16)

Wednesday, August 10, 2022 1:14:23 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment