我想知道如何传递SwitchParameter作为参数。
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)] [System.Management.Automation.SwitchParameter] $FrequencyToExecute #e.g. -Once, -Daily, -Weekly, -DaysInterval...
, [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}
)
$Trigger= New-ScheduledTaskTrigger -At $TimeToExecute -Once # Specify the trigger settings
$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
}
ExecuteWindowsTaskScheduler "Open Notepad task" "11:56am" -Once "xxx\yyy" "C:\PowerShell\OpenNotepad.ps1"
我有参数$FrequencyToExecute
,当我调用该函数时,我希望能够传递以下命令之一: -Once , -Daily < / kbd>,-每周等
有可能吗?我该怎么办?
答案 0 :(得分:5)
您可能希望将参数类型更改为[string]
,然后使用[ValidateSet]
属性来强制执行“ Once”,“ Daily”或“ Weekly”的值,然后使用{{ 3}},将适当的开关传递给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
}
答案 1 :(得分:1)
我相信您正在寻找parameter sets
您将定义所有需要的参数,但是每个参数都将在一个不同名称的ParameterSet中。这使得它们在进行参数绑定时是互斥的。