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")
CodePudding user response:
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