Use Get-Date "time" in an "if" statement PowerShell - 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.

Related

Powershell - Determine Sunset and Add Time

I have a Powershell script that determines my local sunrise and sunset. However, my end goal is to run a function at 45 minutes past sunset. I know I can't use AddMinutes(45) as that only works with Get-Date. I tried to format the output of the value returned for "sunset", but even formatted to match Get-Date, it still doesn't work. Is there some other method I could use?
$Daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=35.608081&lng=-78.647666&formatted=0").results
$Sunrise = ($Daylight.Sunrise | Get-Date -Format "HH:mm")
$Sunset = ($Daylight.Sunset | Get-Date -Format "dddd, MMMM dd, yyyy hh:mm:ss tt")
If you're using PowerShell Core, the properties Sunrise and Sunset from the object returned by your API query should already be of the type DateTime, however in Windows PowerShell, you would need to cast [datetime] to them to convert them from string. Then .AddMinutes method would work without issues, if you're looking to run a function 45 minutes past Sunset you can try the following assuming this could be a scheduled task:
$Daylight = (Invoke-RestMethod "urlhere").results
$sunset = [datetime] $Daylight.sunset # => [datetime] only needed in Windows PowerShell
if([datetime]::Now -ge $sunset.AddMinutes(45)) {
# run function here
}
Or if you want your script to execute and wait until the right time, you can use a loop:
do {
Start-Sleep -Seconds 60
} until([datetime]::Now -ge $sunset.AddMinutes(45))
# run function here

Testing if now if between two times that span midnight

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"}

Powershell keep looping until condition is true then proceed

I have written a script that so far is able to check a file "latest.json" for the "created_at" object which shows the last date that a commit has occurred for software.
$websiteJson = Invoke-WebRequest "https://website/latest.json" | ConvertFrom-Json | select created_at
$todaysDate = Get-Date -Format "yyyy-MM-dd HH:mm"
if($websitejson.created_at | where {$_.created_at -eq $todaysDate}){
Write-Output "Today's date matches"
} else {
Write-Output "has not yet been updated"
}
How part of latest.json looks like
"created_at":"2020-03-23 17:32:48"
How do I change this to keep looping until the date pull from latest.json matches then proceed to next step (would download and install software). Also, since "created at" has "17:32:48" will this cause the date check to fail since the time does not match?
. I want it to keep checking if dates match.
Thank you!
Right now, I'm not going to bother converting dates to match to make sure they're the same format, but what you need for your specific questions is just a do until loop. I might update this to check the date formats if you supply an example layout of the returned JSON.
Do{
$websiteJson = Invoke-WebRequest "https://website/latest.json" | ConvertFrom-Json | select created_at
$todaysDate = Get-Date -Format "yyyy-MM-dd HH:mm"
if($websitejson.created_at | where {$_.created_at -eq $todaysDate}){
Write-Output "Today's date matches"
} else {
Write-Output "has not yet been updated"
}
start-sleep -s 60
}until($websiteJson -eq $todaysDate)
I believe this wont work right off the bat. You'll have to get the JSON date and $todaysDate to be the same format, then you can do this and it will work.
if you want to compare the date and/or time, use datetime objects instead of datetime strings. something like this ...
if you want to test for the actual time difference between two time objects ...
((Get-Date -Date '2020-03-23 18:11:22') - [datetime]'2020-03-23 17:32:48').TotalHours
# result = 0.642777777777778
you keep mentioning date as if you don't want the time, so this method would work for comparing the date parts of two timestamps ...
# the date at the time the code was run = 2020 April 03, Friday 4:30:34 PM
$Today = (Get-Date).Date
$Created_At = '2020-04-03 15:15:15'
$Today -eq ([datetime]$Created_At).Date
result = True

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

PowerShell - formatting date to yyMMdd format

I run a PowerShell script that passes a parameter, such as "20160428".
I need to format this into yyMMdd (i.e., getting "160428" as the result). I could just strip out the "20", but I would like to get this right. For such I did so many attempts, such as:
#$COBDATE= '{0:yyMMdd}' -f $COBDATE
#$COBDATE = ([datetime]::ParseExact($COBDATE, "yyMMdd", [System.Globalization.CultureInfo]::InvariantCulture )).DayOfWeek
And the last one:
$COBDATE = ("{0:yyMMdd}" -f [datetime]::parse($COBDATE))
The below works, but once I replace "Get-Date" by my date "20160428" it just prints out the yyMMdd string.
$b = (Get-Date).AddDays(-1).ToString("yyMMdd")
So if I try this:
$input = "20160428"
$format = "yyMMdd"
$input_toDate_up = [DateTime]::ParseExact($input, $format, $null).ToString($format)
$input_toDate_up
It just says that the string is not a valid Date Time, which seems to be the root cause.
How can I fix this?
$Input = "20160428"
Get-Date -Year $Input.Substring(0,4) -Month $Input.Substring(4,2) -Day $Input.Substring(6,2) -Format "yyMMdd"
I think for one $input is a reserved variable so you shouldn't use it as nothing will really work in there as you expect. See here about_Automatic_Variables
I have used this drawn out substring process before with varied abstract date formats.
$dateinput = "20160428"
$dateformat = "yyMMdd"
Get-Date($dateinput.Substring(4,2) + "/" + $dateinput.Substring(2,2) + "/" + $dateinput.substring(0,4)) -Format $dateformat
I'm sure there is a shorter regex method, but that is not under my hat yet.