PowerShell Run if Day and Hour

I am trying to write a PowerShell script to run a segment of code if the day and hour match:

if it is Monday 10am hour run:

if it is Monday 6pm hour run:

If it is Sunday 7pm hour run:


I have found several bulky ways of doing this but I am trying to keep things tight. Any ideas?
Who is Participating?
becraigConnect With a Mentor Commented:
Easy solution
        $hour= Get-Date -Format HH
        $day = Get-Date -Format dddd
 if ($day -eq "Monday" -and $hour -eq "10")
Execute something
 if ($day -eq "Sunday" -and $hour -eq "7")
Execute something

You can also write your day into a switch if this will be daily / hourly
SeanSystem EngineerCommented:
why not do a scheduled task to run the script at those times?
-TNT-Author Commented:
Because there are a total of about 12 tasks that need to be run and on several computers. So to schedule 12 tasks on 5 computers will take a long time, plus if we replace a computer we have to do it all over again.
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

SeanSystem EngineerCommented:
what you can do is get-date -format ddd to get the day of the week and get-date -format hh:mm to get the time. Then you can do an if statement to check those to run your script and then put everything in large loop with a sleep timer.
Here's another method.  Just substitute your action for "First", "Second", etc.
switch (Get-Date)
    {$_.dayofweek -eq "Monday" -and $_.Hour -eq 10}
        { "First"}
    {$_.dayofweek -eq "Monday" -and $_.Hour -eq 18}
        { "Second" }
    {$_.dayofweek -eq "Sunday" -and $_.Hour -eq 19}
        { "Third" }

Open in new window

QlemoBatchelor and DeveloperCommented:
Are the tasks the same for all machines? If so, running a PS script on one "server" doing the task scheduling might be a better approach. Or let that single machine run 12 tasks, each performing the same action for a list of machines.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.