有一种方法你可以通过命令行使用powerhell来实现。
将这段代码添加到一个名为MyModule.psm1的文件中。
$TASK_STATE_UNKNOWN = 0;
$TASK_STATE_DISABLED = 1;
$TASK_STATE_QUEUED = 2;
$TASK_STATE_READY = 3;
$TASK_STATE_RUNNING = 4;
Function Run-Task(
[ValidateNotNullOrEmpty()][string]
[Parameter(Mandatory=$true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
$ComputerName,
[ValidateNotNullOrEmpty()][string]
[Parameter(Mandatory=$true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
$Foldername,
[ValidateNotNullOrEmpty()][string]
[Parameter(Mandatory=$true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
$Taskname,
[int] $maxwait = 0,
[string[]]
[Parameter(Mandatory=$false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
$TaskParameters = $null
){
$TaskScheduler = New-Object -ComObject Schedule.Service
$TaskScheduler.Connect($ComputerName)
$ScheduledTaskFolder = $TaskScheduler.GetFolder($Foldername)
$ScheduledTask = $ScheduledTaskFolder.GetTask($TaskName)
if(-not $ScheduledTask) {
return $Null
}
$ScheduledTask.Enabled = $True
$ScheduledTask.Run($TaskParameters)
if($maxwait -gt 0){
$seconds = 5
$i = 0;
Start-Sleep -Seconds $seconds
while ($ScheduledTask.State -eq $TASK_STATE_RUNNING)
{
if(($i * $seconds) -gt $maxwait) {
break;
}
Start-Sleep -Seconds $seconds
$i++;
}
}
return $ScheduledTask
}
Export-ModuleMember -Variable "TASK_STATE*"
Export-ModuleMember -Function "Run-*"
然后从命令行或ps1文件中你可以运行。
Import-Module $(Get-Item .\MyModule.psm1 | Resolve-Path -Relative) -DisableNameChecking -Force
$task = Run-Task -ComputerName "$env:COMPUTERNAME" -Taskname "Foo" -Foldername "\" -TaskParameters "test", "Tim C", $(Get-Date -format G)
taskparameters数组中的每一项都会以$(Arg0)、$(Arg1)和$(Arg2)的形式传递进来。