计划任务不会运行

时间:2017-09-20 15:54:20

标签: powershell

整个剧本。

$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "$getservice = Get-Service -Name wuauserv; If($getservice.Status -eq 'Running') {Start-Sleep -s 10; Start-Process -FilePath D:\1.bat} Else {Start-Process -FilePath D:\1.bat}"
$trigger =  New-ScheduledTaskTrigger -Weekly -At 9am -DaysOfWeek Thursday -WeeksInterval 4
$settings = New-ScheduledTaskSettingsSet -Compatibility Win8 -StartWhenAvailable
$principal = New-ScheduledTaskPrincipal -UserID System -RunLevel Highest
$params = @{
"TaskName"  = "Office"
"Action"    = $action
"Trigger"   = $trigger
"Settings"  = $settings
"Principal" = $principal
}
Register-ScheduledTask @Params -Force

1.bat由一行"记事本"例如。但是当我启动任务时没有任何反应。导入的Withal脚本没有任何错误。 所以问题是我在哪里弄错了

$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "$getservice = Get-Service -Name wuauserv; If($getservice.Status -eq 'Running') {Start-Sleep -s 10; Start-Process -FilePath D:\1.bat} Else {Start-Process -FilePath D:\1.bat}"

此代码确实运行!

$getservice = Get-Service -Name wuauserv; If($getservice.Status -eq 'Running') {Start-Sleep -s 10; Start-Process -FilePath D:\Программы\Прочее\1.bat} Else {Start-Process -FilePath D:\1.bat}

1 个答案:

答案 0 :(得分:0)

当我将第一行改为此时,我能够让您的代码成功运行:

$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "`$getservice = Get-Service -Name wuauserv; If(`$getservice.Status -eq 'Running') {Start-Sleep -s 10; Start-Process -FilePath D:\1.bat} Else {Start-Process -FilePath D:\1.bat}"

请注意代码中美元符号前面的反引号。您必须转义美元符号,否则PowerShell会将它们视为变量并对其进行插值,这会将您要发送给您任务的PowerShell命令大打折扣。

我无法用"记事本测试1.bat"因为我不会看到它以我身份登录,所以我将它用于1.bat:

rem notepad.exe
echo Test123 >> D:\1.txt