PowerShell – Using Variable for -DaysofWeek in New-ScheduledTaskTrigger

powershellscheduled-task

I'm writing a script that takes the user's input to then Register-ClusteredScheduledTask
I'm trying to use a string for the -DaysOfWeek, but am only receiving various errors…

New-ScheduledTaskTrigger -Weekly -WeeksInterval $recur -DaysOfWeek $day -At $starttime

New-ScheduledTaskTrigger: Cannot process argument transformation on parameter 'DaysOfWeek'. Cannot convert value "[dayofweek]Sunday,Wednesday,Saturday" to type "System.DayOfWeek[]". Error: "Cannot convert value "[dayofweek]Sunday,Wednesday,Saturday" to type "System.DayOfWeek". Error: "Unable to match the identifier name [dayofweek]Sunday,Wednesday,Saturday to a valid enumerator name. Specify one of the following enumerator names and try again:
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday""

I did notice that when setting for individual days, the system assigns each day with a 64bit number, starting with Sunday at 1 thru Saturday at 64…

Enabled            : True
EndBoundary        :
ExecutionTimeLimit :
Id                 :
Repetition         :
StartBoundary      : 2020-03-28T02:00:00Z
DaysOfWeek         : 64
RandomDelay        :
WeeksInterval      : 1
PSComputerName     :

Therefore, if I schedule the following, I get the addition of Sunday + Saturday…

PS C:\Scripts\DCS> New-ScheduledTaskTrigger -Weekly -WeeksInterval $recur -DaysOfWeek Sunday,Saturday -At $starttime


Enabled            : True
EndBoundary        :
ExecutionTimeLimit :
Id                 :
Repetition         :
StartBoundary      : 2020-03-28T02:00:00Z
DaysOfWeek         : 65
RandomDelay        :
WeeksInterval      : 1
PSComputerName     :

How can I use a variable for the -DaysOfWeek and actually work without throwing some sort of error?

I've tried various methods of converting the string to date, with limited success.

When I use [dayofweek]$day = 'Sunday,Saturday'

$day is only = to Saturday

Best Answer

With [dayofweek]$day you are defining a single value variable. You need to define it as an array:

$ [dayofweek[]]$day = 'Sunday','Saturday'