Increment hours by 30 minutes 20 times in Powershell - powershell

I have to create multiple job in my app. These jobs should be separated by 30 minutes apart starting at 17:00. My dilemma how to get 20 times in hour and minutes ( HH:MM) format starting at 17:00 ?? Onces i have those times , i can loop all jobs 30 minutes apart.
Thank you
So far i have tried
$ts = New-TimeSpan -Hours 17 -Minutes 00
But adding minutes to $ts not working
PS F:\> $ts.AddMinutes(30)
Method invocation failed because [System.TimeSpan] does not contain a method named 'addminutes'.
At line:1 char:1
+ $ts.AddMinutes(30)
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

You can simply add a new timespan:
$newts = $ts + (New-TimeSpan -Minutes 30)

You can add a string that will automatically convert to type [timespan], since the left argument is [timespan]:
$ts = [timespan]'17:30'
$ts += '0:30'
$ts
Days : 0
Hours : 18
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 648000000000
TotalDays : 0.75
TotalHours : 18
TotalMinutes : 1080
TotalSeconds : 64800
TotalMilliseconds : 64800000

Paolo's helpful answer shows how to add a timespan to an existing timespan, where the + operation translates to the [timespan] type's .Add() method.
By contrast, it is the [datetime] / [datetimeoffset] types that have an .AddMinutes() .AddMinutes() method.
Therefore, you could do the following:
# Get today's date at 17:00 hours
$start = Get-Date -Hour 17 -Minute 0 -Second 0 -MilliSecond 0
# Loop 20 times and add 30 minutes each, and format as "HH:mm"
0..19 | ForEach-Object { $start.AddMinutes($_ * 30).ToString('HH:mm') }
Output:
17:00
17:30
18:00
18:30
19:00
19:30
20:00
20:30
21:00
21:30
22:00
22:30
23:00
23:30
00:00
00:30
01:00
01:30
02:00
02:30

Related

Converting string to timespan

Im new to powershell and Ive been trying to convert this string to a timespan object:
"2 Days 1 Hour 15 Minutes"
Ive tried several ways to input the format using parseexact but I cant seem to get the right format down.
Ive tried something like this :
[TimeSpan]::ParseExact('2 Days 1 Hour 15 Minutes', 'd \Days h \Hour MM \Minutes', $null)
The TimeSpan parser is very sensitive, you need to escape everything that isn't a format string specifier:
[TimeSpan]::ParseExact('2 Days 1 Hour 15 Minutes', '%d\ \D\a\y\s\ %h\ \H\o\u\r\ %m\ \M\i\n\u\t\e\s', $null)
(I used the percent-sign notation for the specifiers (%d instead of d) to make them stand out in amongst all the \'s, but they're not required)
The string version normally looks like this: '2.01:15:00', so [timespan]'2.01:15' works.
I am glad to see you have an answer. Another way would be to use named captures in a regex.
PS C:\> '2 Days 1 Hour 15 Minutes' -match '^(?<Days>\d+)\D*(?<Hours>\d+)\D*(?<Minutes>\d+)\D*'
True
PS C:\> $matches
Name Value
---- -----
Hours 1
Minutes 15
Days 2
0 2 Days 1 Hour 15 Minutes
PS C:\> $Matches.Days
2
PS C:\> $Matches.Hours
1
PS C:\> $Matches.Minutes
15
PS C:\> $Ts = New-TimeSpan -days $Matches.Days -Hours $Matches.Hours -Minutes $Matches.Minutes
PS C:\> $Ts
Days : 2
Hours : 1
Minutes : 15
Seconds : 0
Milliseconds : 0
Ticks : 1773000000000
TotalDays : 2.05208333333333
TotalHours : 49.25
TotalMinutes : 2955
TotalSeconds : 177300
TotalMilliseconds : 177300000

Add Time from TimeSpan Object in Powershell

This has been driving me nuts, and it's got to be something simple I'm missing.
I'm simply trying to get the total hours from a TimeSpan object and use that to add to a DateTime object.
$mytime = "1/1/2020 10:00:00"
$hours = (New-TimeSpan -Start $mytime).TotalHours
Get-Date
(Get-Date $mytime).AddHours($hours)
The result is
Wednesday, February 5, 2020 11:25:37 AM
Wednesday, February 5, 2020 11:25:37 AM
In the above, the time doesn't change! However if I just assign a value to $hours, it works fine.
$mytime = "1/1/2020 10:00:00"
$hours = 100
Get-Date
(Get-Date $mytime).AddHours($hours)
Wednesday, February 5, 2020 11:25:37 AM
Sunday, January 5, 2020 5:00:01 AM
I've tried all manner of variable assignments and casting, but no matter what I do I can't get the TotalHours value to work. Why can't I use $hours? TotalHours is supposed to be a normal double, and even if I cast it to double ([double]$hours = New-Timespan...) nothing changes.
TotalHours includes fractional hours. The value of $hours will be something like 844.1311..... The value of TotalHours is basically:
$ts = New-TimeSpan -Start $mytime
$ts.Ticks / [TimeSpan]::TicksPerHour
If you want the integer value, try:
$mytime = "1/1/2020 10:00:00"
$hours = [math]::Truncate((New-TimeSpan -Start $mytime).TotalHours)
(Get-Date $mytime).AddHours($hours)
I haven't tested it, but you might need to use Math.Floor() instead if you can potentially have $mytime in the future.
Truthfully, though, if you want the same hour of day today as another date, it's more logical to do this:
$mytime = Get-Date "1/1/2020 10:00:00"
$today = (Get-Date).Date
$today.AddHours($mytime.Hour)
Or:
$mytime = Get-Date "1/1/2020 10:00:00"
[DateTime]::Today.AddHours($mytime.Hour)
It works for me. You're adding 844.4 hours (35 days) in the first example, the number of hours to get to the current day and time, and 100 hours (4 days) in the second.
$mytime = "1/1/2020 10:00:00"
$hours = (New-TimeSpan -Start $mytime).TotalHours
$hours
844.404845696333
(Get-Date $mytime).AddHours($hours)
Wednesday, February 5, 2020 2:24:17 PM
$mytime = "1/1/2020 10:00:00"
$hours = 100
(Get-Date $mytime).AddHours($hours)
Sunday, January 5, 2020 2:00:00 PM
Here's another example:
[datetime]'2:28pm' + (new-timespan -Hours 1)
Wednesday, February 5, 2020 3:28:00 PM
If it's under 24 hours, it can be as simple as ([timespan] is implied in the 2nd argument):
[datetime]'2:28pm' + '1:0'
Wednesday, February 5, 2020 3:28:00 PM
Subtracting two datetimes:
[datetime]"Wednesday, February 5, 2020 11:25:37 AM" - [datetime]"1/1/2020 10:00:00"
Days : 35
Hours : 1
Minutes : 25
Seconds : 37
Milliseconds : 0
Ticks : 30291370000000
TotalDays : 35.0594560185185
TotalHours : 841.426944444444
TotalMinutes : 50485.6166666667
TotalSeconds : 3029137
TotalMilliseconds : 3029137000

PowerShell date time conversion issue

When I run the below two PowerShell statements, I expect them to return the same result, but in fact they return different results:
New-TimeSpan $(Get-Date) $(Get-Date -month 12 -day 31 -year 2016)
New-TimeSpan $(Get-Date) $(Get-Date "2016-12-31")
The results are:
Days : 751
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 1
Ticks : 648864000010001
TotalDays : 751.000000011575
TotalHours : 18024.0000002778
TotalMinutes : 1081440.00001667
TotalSeconds : 64886400.0010001
TotalMilliseconds : 64886400001.0001
Days : 750
Hours : 6
Minutes : 50
Seconds : 13
Milliseconds : 67
Ticks : 648246130673175
TotalDays : 750.284873464323
TotalHours : 18006.8369631437
TotalMinutes : 1080410.21778863
TotalSeconds : 64824613.0673175
TotalMilliseconds : 64824613067.3175
What's going on?
I'm pretty sure the answer is in the different parameter sets you are using. Referring to the TechNet article. There are two different parameter sets: net and uformat
Get-Date "2016-12-31" is is being detected as net
(Get-Date -month 12 -day 31 -year 2016) is being detected as uformat
In the latter, since you are not specifying the time components, it is defaulting them to the current time. Looking at the documentation for -Hour
-Hour<Int32>
Specifies the hour that is displayed. Enter a value from 1 to 23. The default is the current hour.
When the string "2016-12-31" is cast to a datetime midnight, it is used in the absence of a value. In the other case no time is specified, so it is using the current time in its place.
PS C:\Users\Cameron> (Get-Date -month 12 -day 31 -year 2016)
Saturday, December 31, 2016 5:14:32 PM
PS C:\Users\Cameron> $(Get-Date "2016-12-31")
Saturday, December 31, 2016 12:00:00 AM
I might be slightly wrong on the terms or cause, but I have to be close. Even when specifying hour for example the other time values still need to come from somewhere. The time when the code was run was 5:24 pm EST.
PS C:\Users\Cameron> (Get-Date -month 12 -day 31 -year 2016 -Hour 12)
Saturday, December 31, 2016 12:24:43 PM

New-TimeSpan cmdlet in powershell

How can i use New-Timespan cmdlet to calculate the total time taken for script execution.I tried a sample like this.
$val=Get-Date
$start=New-TimeSpan -Start $val
$val2=Get-Date
$end=New-TimeSpan -End $val2
$diff=New-TimeSpan -Start $start -End $end
But ended up with following error: New-TimeSpan : Cannot bind parameter 'Start'. Cannot convert the "00:00:08.7110000" value of type "System.TimeSpan" to
type "System.DateTime".
You don't need to use New-TimeSpan just subtract the DateTime objects:
$script_start = Get-Date
Start-Sleep -Seconds 5
$script_end = Get-Date
$script_end - $script_start
This will create a TimeSpan object.
You could use Measure-Command. It returns a timespan object. Example:
PS C:\> Measure-Command -Expression {1..10000000}
Days : 0
Hours : 0
Minutes : 0
Seconds : 1
Milliseconds : 714
Ticks : 17149279
TotalDays : 1.98487025462963E-05
TotalHours : 0.000476368861111111
TotalMinutes : 0.0285821316666667
TotalSeconds : 1.7149279
TotalMilliseconds : 1714.9279

Converting time 121.419419 to readable minutes/seconds

I'd like to calculate the time my script runs, but my result from get-date is in totalseconds.
How can I convert this to 31:14:12 behing hours:minutes:seconds?
PS> $ts = New-TimeSpan -Seconds 1234567
PS> '{0:00}:{1:00}:{2:00}' -f $ts.Hours,$ts.Minutes,$ts.Seconds
06:56:07
or
PS> "$ts" -replace '^\d+?\.'
06:56:07
All you have to do is use the Measure-Command cmdlet to get the time:
PS > measure-command { sleep 5}
Days : 0
Hours : 0
Minutes : 0
Seconds : 5
Milliseconds : 13
Ticks : 50137481
TotalDays : 5.80294918981481E-05
TotalHours : 0.00139270780555556
TotalMinutes : 0.0835624683333333
TotalSeconds : 5.0137481
TotalMilliseconds : 5013.7481
The above output itself might be good enough for you, or you can format it appropriately as the the output of Measure-Command is a TimeSpan object. Or you can use ToString:
PS > (measure-command { sleep 125}).tostring()
00:02:05.0017446