Testing if now if between two times that span midnight - powershell

I've tried searching for this, but I'm at a loss... I can find answers for other languages, but not for PowerShell.
Basically, I want to test if the time now is between 21:15 and 5:45.
I'm pretty sure I need to use New-TimeSpan - but, for the life of me, I just can't work it out.
I'd share my test code, but I think I'm so far away from the answer that it wouldn't be of any help.
Can anyone help me?

Use Get-Date to create DateTime objects describing those thresholds as points in time on todays date, then test if the time right now is before the early one or after the late one:
$now = Get-Date
$morning = Get-Date -Date $now -Hour 5 -Minute 45
$evening = Get-Date -Date $now -Hour 21 -Minute 15
$isWithinRange = $now -le $morning -or $now -ge $evening

If this is purely about the time of day and you don't need any date calculations, you can do the following, relying on the fact that for padded number strings lexical sorting equals numeric sorting:
# Get the current point in time's time of day in 24-hour ('HH') format.
# Same as: [datetime]::Now.ToString('HH\:mm')
$timeNow = Get-Date -Format 'HH\:mm'
$timeNow -ge '21:15' -or $timeNow -le '05:45'

If you'd have to check if you are in the range 23:00-04:00, crossing the midnight, you could:
$now=(Get-Date).TimeofDay
if ($now.TotalHours -ge 23 -or $now.TotalHours -lt 04)
{"In Range"}
else
{"Out of range"}

Related

How convert a future date to the yyyy-mm-ddT00:00:00Z format with PowerShell

I am trying to get this to work in PowerShell with no success.
I would need to convert a future date and time (let's say July 1st 2022 midnight 00:00) to the format yyyy-mm-ddT00:00:00Z
The below command:
Get-Date -Format u
outputs to 2022-06-21 13:34:20Z (at the time of writing), which is pretty close to what i need for the present time.
Is there a way to get what i need without the use of regex or replace() method and also in the future?
The format is pretty flexible. Just specify it manually:
Get-Date -Format yyyy-MM-ddTHH:mm:ssZ
Output: 2022-06-21T03:51:17Z
For a future date, it's probably easier to create that in advance, then use it with the formatting:
$futuredate = (Get-Date).AddDays(30)
Get-Date $futuredate -Format "yyyy-MM-ddTHH:mm:ssZ"
Output: 2022-07-21T03:56:46Z
Or, if in your case you really do want exactly midnight for the day in question:
$futuredate = (Get-Date).AddDays(10).Date
Get-Date $futuredate -Format "yyyy-MM-ddTHH:mm:ssZ"
Output: 2022-07-01T00:00:00Z
Based on the above answer, i tried to come up with a version of getting the first day of the next month and the last day. Let me know your thoughts:
Beggining of month:
Get-Date -Format "yyyy-MM-ddT00:00:00Z" -Date ([datetime](Get-Date -Day 1).AddMonths(1))
Output: 2022-07-01T00:00:00Z
End of month:
Get-Date -Format "yyyy-MM-ddT23:59:59Z"-Date (([datetime](Get-Date -Day 1).AddMonths(2)).AddDays(-1))
Output: 2022-07-31T23:59:59Z

How can I get the years months lapsed difference from a certain date with powershell custom date?

I cannot get the time difference from a certain date using Powershell like below:
$Date = '11/12/2001'
(New-TimeSpan -Start (Get-Date -Date $Date) -End (Get-Date)).ToString("'yyyy' Years 'MM' Months 'dd' Days 'hh' Hours 'mm' Minutes 'ss' Seconds'")
Error:
Exception calling "ToString" with "1" argument(s): "Input string was not in a correct format."
At line:2 char:1
+ (New-TimeSpan -Start (Get-Date -Date $Date) -End (Get-Date)).ToString ...
Why I cannot get the Years and Months elapsed?
Why are you even creating the TimeSpan manually? If you subtract a [DateTime] object from another from another PowerShell will return a System.TimeSpan instance.
Example:
$Date1 = Get-Date "8/1/2020 4:00 PM"
$Date2 = Get-Date
$Date2 - $Date1
I know a general principal is to stick with cmdlets where we can but one has to admit this is way cleaner.
There are standard format strings for TimeSpan objects documented here and custom format strings documented here .
I must admit though I don't fully understand this topic, and these formats seems to come out similar looking.
Here are a few examples on top of Olaf's fine answer
$TS = ($date2 - $date1)
"{0:dd} Days, {0:hh} Hours, {0:mm} Minutes, {0:ss} Seconds" -f $TS
A kludge-y approach:
$TS.ToString( "%d\D%h\H%m\M%s\S" ).Replace("D", " Days, " ).Replace("H", " Hours, " ).Replace("M", " Minutes, ").Replace( "S", " Seconds")
Another fairly hideous thing you can do:
$TS.ToString('dd\ \d\a\y\s\,\ hh\ \H\o\u\r\s\ mm\ \M\i\n\u\t\e\s\ ss\ \S\e\c\o\n\d\s\')
You're using the notation for dates. A timespan object does have this I think. You could use something like this:
$Date = '11/12/2001'
$TS = New-TimeSpan -Start (Get-Date -Date $Date) -End (Get-Date)
"{0} days, {1} hours, {2} minutes, {3} seconds" -f $TS.Days, $TS.Hours, $TS.Minutes, $TS.Seconds
Output $TS as it is to see what you can use. ;-)
$TS

PowerShell returns 2 as week number on January 06 2020

A quick question, apparently today (January 06, 2020) week number should be 2, because there are 53 weeks in 2020.
However, the following PowerShell snippet returns 1:
(Get-Date -UFormat %V)
What is the good approach getting the week number properly?
To translate this Get the correct week number of a given date C# answer from #il_guru into PowerShell:
Function GetIso8601WeekOfYear([DateTime]$Date) {
$Day = (Get-Culture).Calendar.GetDayOfWeek($Date)
if ($Day -ge [DayOfWeek]::Monday -and $Day -le [DayOfWeek]::Wednesday) {$Date = $Date.AddDays(3)}
(Get-Culture).Calendar.GetWeekOfYear($Date, 'FirstFourDayWeek', 'Monday')
}
GetIso8601WeekOfYear (Get-Date)
2
GetIso8601WeekOfYear (Get-Date('2016-01-01'))
53
You could detect a leap year and then adjust the week number based off the result.
if(((Get-Date).year)%4 -eq 0){
$week = (Get-Date -UFormat %V) -as [int]
$week++
}else{
$week = (Get-Date -UFormat %V)
}
Write-Host $week

Using Time in a conditional Statement in Powershell

I'm trying to just get the groundwork for running some code with a time conditional. But I can't seem to grasp how to add time into the equation. Any Powershell people out there?
The $EndDate doesnt matter anymore. I just tried to use it as a way to understand how powershell uses conditional
$StartTime=(Get-Date)
$EndDate=[datetime]”00:00”
if ($StartDate -gt "00:00" -and $StartTime -lt "11:59")
{
Write-Host "It is time to work"
}
else
{
Write-Host "it is time to go"
}
$StartTime
My code right now should say its time to go but should say its time to work because as of right now its only 11:56 AM ET.
If you want to compare against the time of day, use the TimeOfDay TimeSpan exposed by [datetime] - PowerShell will automatically convert the right-hand "HH:mm" string into a meaningful TimeSpan that can be compared against:
$StartTime = Get-Date
if($StartTime.TimeOfDay -gt "00:00" -and $StartTime.TimeOfDay -le "12:00"){
# AM
}
else{
# PM
}
These two things are usually true.
(get-date) -gt '00:00'
True
(get-date) -lt '23:59'
True
Check for unset variables:
set-strictmode -v 1

Use Get-Date "time" in an "if" statement PowerShell

$WshShell = New-Object -ComObject wscript.shell
$Time = (Get-Date).hour
$Time2 = Get-Date -DisplayHint Time
$Message ="Test for $Env:username at: " + $Time2
$fail = "ERROR:It is $Time2, which is past 12PM"
$PopUp = $WshShell.popup("$Message",0,"Task Scheduler Pop-up",1)
if ($Time2 > 12)
{
$PopUp = $wshShell.popup("$Message",0,"Task Scheduler Pop-up",1)
}
else {
$PopUp = $wshShell.popup("$fail",2,"Task Scheduler Pop-up",1)
}
Hi guys, I'm practicing a little bit of my PowerShell and have run across something I'm not quite sure how to Google for, or what method I need to use to get this to work correctly.
What I'm attempting to accomplish is have my box display only, the hour and minute like "12:31".
As you can see in the script I'm calling the
Hour, but I can't quite figure out how to have it display the time by itself the right way. I'm using the "Time" operator, but when you compare that in the "IF" statement, it doesn't recognize it as something it can compare itself to since it's not a real integer. I understand why, but I would like to be able to compare the .Hour to $Time2
I'm new to this and appreciate any help you can provide!
Thank you!
Don't think in terms of output strings before you actually need to.
> won't work for comparisons, you need to use -lt (less than) and -gt (greater than)
If you want to compare the time of two DateTime objects (regardless of the date), you can compare the TimeOfDay property:
$DateTimeNow = Get-Date
$DateTimeEarly = Get-Date -Hour 1 -Minute 5
if($DateTimeNow.TimeOfDay -lt $DateTimeEarly.TimeOfDay){
"It is very early right now!"
} else {
"It is at least past 01:05"
}
If you want to show the time in output, you have multiple options for formatting a DateTime string:
You can use the ToString() method with a formatting string:
PS C:\> (Get-Date).ToString('HH:mm')
20:41
The format operator -f:
PS C:\> '{0:HH:mm}' -f (Get-Date)
20:41
Or have Get-Date return a formatted string itself:
PS C:\> Get-Date -Format 'HH:mm'
20:41
If you want 12-hour style time, use hh:mm
If you need to display the time you could use one of several methods. Those would all convert the result to string. I think you need to save $time2 as just a [datetime] object. That way you can format it for display and use .Hour for comparison logic.
$Time2 = Get-Date
$Message ="Test for $Env:username at: " + $Time2.ToString("HH:mm")
$PopUp = $WshShell.popup("$Message",0,"Task Scheduler Pop-up",1)
if ($Time2.Hour -gt 12){
#Do Stuff
}
This logic would only work for 24hr time though. 1(pm) is less than 12 but later in the day. Which is what HH:mm represents.