Возможно, вы захотите изменить тип параметра на [string]
, а затем использовать атрибут [ValidateSet]
, чтобы задать значение «Once», «Daily» или «Weekly», а затем использовать splatting передать соответствующий переключатель на New-ScheduledTaskTrigger
:
function ExecuteWindowsTaskScheduler {
param(
[Parameter(Mandatory = $true)]
[String]$TaskName, #e.g. "Open Notepad task"
[Parameter(Mandatory = $true)]
[String]$TimeToExecute, #e.g. "3:45pm/am"
[Parameter(Mandatory = $true)]
[ValidateSet('Once','Daily','Weekly','Monthly')]
[string]$FrequencyToExecute, #e.g. -Once, -Daily, -Weekly, Monthly
[Parameter(Mandatory = $true)]
[String]$DomainAndUser, #e.g. "yourdomain\yourusername"
[Parameter(Mandatory = $true)]
[String]$ProgramWithPath, #e.g. "C:\PowerShell\yourFile.ps1"
[Parameter(Mandatory = $false)]
[bool]${DebugMode}
)
$TriggerParams = @{
At = $TimeToExecute
}
# Add the appropriate frequency value to the splatting table
if ($FrequencyToExecute -eq 'Monthly') {
$TriggerParams.Add('Weekly',$true)
$TriggerParams.Add('WeeksInterval',4)
$TriggerParams.Add('DaysOfWeek','Monday')
}
elseif ($FrequencyToExecute -eq 'Weekly') {
$TriggerParams.Add('Weekly',$true)
$TriggerParams.Add('WeeksInterval',1)
$TriggerParams.Add('DaysOfWeek','Monday')
}
else {
$TriggerParams.Add($FrequencyToExecute,$true)
}
$Trigger = New-ScheduledTaskTrigger @TriggerParams
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $ProgramWithPath # Specify what script to run and with its parameters
$TaskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $TaskName }
Register-ScheduledTask -TaskName $TaskName -Trigger $Trigger -User $DomainAndUser -Action $Action
}