使用PowerShell安排运行可执行文件

时间:2016-05-25 13:04:39

标签: powershell scheduled-tasks

我需要编写一个脚本,它将创建任务调度程序作业,在pc启动时将运行可执行文件。简而言之,脚本将是这样的:

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:10
Register-ScheduledJob -Trigger $trigger -Name FileJob -ScriptBlock {$args[0]}

但它不起作用。怎么了?

2 个答案:

答案 0 :(得分:2)

我使用以下Powershell代码段来创建Windows计划任务。

$action = New-ScheduledTaskAction -Execute 'application.exe' -Argument '-NoProfile -WindowStyle Hidden'
$trigger =  New-ScheduledTaskTrigger -AtStartup -RandomDelay 00:00:10
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "FileJob" -Description "FileJob"

答案 1 :(得分:0)

这是我用来创建任务的:

#The first command uses the New-ScheduledTaskAction cmdlet to assign the action variable $A to the executable file tskmgr.exe
$A = New-ScheduledTaskAction -Execute "C:\WINDOWS\SysWOW64\WindowsPowerShell\v1.0\powershell.exe" -file "C:\directory\powershell.ps1"

#The second command uses the New-ScheduledTaskTrigger cmdlet to assign the trigger variable $T to the value AtLogon
$T = New-ScheduledTaskTrigger -weekly -DaysOfWeek Saturday -At 7am

#The third command uses the New-ScheduledTaskSettingsSet cmdlet to assign the settings variable $S to a task settings object
$S = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit 1:00:00 -MultipleInstances 2

#The fourth command assigns the principal variable to the New-ScheduledTaskPrincipal of the scheduled task, Domain\Username
$P = New-ScheduledTaskPrincipal -UserId domain\gMSAaccount$ -LogonType Password -RunLevel Highest

#The fifth command sets the description varible to $D for the task definition
$D = "Insert your description here"

#Registers the new scheduled task and defines it by using the $D variable
Register-ScheduledTask Name_of_Task -Action $A -Trigger $T -Settings $S -Principal $P -Description $D<p>

我发现在活动目录环境中使用gMSA帐户是最好的。 Implement gMSA要求是,为了使用gMSA,您必须使用powershell脚本或schtask.exe创建任务。