Avatar of -TNT-
-TNT-

asked on 

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:

etc.

I have found several bulky ways of doing this but I am trying to keep things tight. Any ideas?
Powershell

Avatar of undefined
Last Comment
Qlemo
Avatar of Sean
Sean
Flag of United States of America image

why not do a scheduled task to run the script at those times?
Avatar of -TNT-
-TNT-

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of becraig
becraig
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Sean
Sean
Flag of United States of America image

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.
Avatar of footech
footech
Flag of United States of America image

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

Avatar of Qlemo
Qlemo
Flag of Germany image

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.
Powershell
Powershell

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

27K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo