创建计划任务时出错

时间:2018-06-21 17:30:41

标签: powershell scheduled-tasks powershell-v5.0 taskscheduler

我正在尝试使用PowerShell 5创建计划的任务。但是在尝试将DeleteExpiredTaskAfter添加到ScheduledTaskSettingsSet

时遇到错误。
  

-DeleteExpiredTaskAfter(新时间跨度-秒120)

下面的PowerShell脚本:

$taskname = "Test01"
$taskdescription = "Testing"
$taskpath = "\Test"

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& D:\Test.ps1 -SqlServer Sql1 -Database UAT -Date 2018-03-01 -Start 07:00:00"'

$trigger =  New-ScheduledTaskTrigger -Once -At (Get-Date -Month 06 -Year 2018 -Day 21 -Hour 9 -Minute 40 -Second 00)

$setting = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Day 3) -Hidden -StartWhenAvailable -DeleteExpiredTaskAfter (New-TimeSpan -Seconds 120) -RunOnlyIfNetworkAvailable

$principal = New-ScheduledTaskPrincipal -UserId "LOCALSERVICE" -LogonType S4U

function ScheduledTask-Exists($taskname) {
    $schedule = New-Object -Com Schedule.Service
    $schedule.connect()
    $taskFolder = $schedule.GetFolder($taskpath)
    $taskExists = $taskFolder.GetTask($taskname) |
                  Select-Object Name |
                  Where-Object { $_.Name -eq $taskName }
    if (-not $taskExists) {
        return $false
    }
    return $true
}

if ((ScheduledTask-Exists($taskname))) {
    Write-Output "$taskname already exists"  
} else {
    Register-ScheduledTask -Action $action -Trigger $trigger -TaskPath $taskpath -TaskName $taskname -Description $taskdescription -Settings $setting -Principal $principal -Force 
    Write-Output "Creating Scheduled Task - $taskName"
}

我遇到的错误:

Register-ScheduledTask : The task XML is missing a required element or
attribute. (49,4):EndBoundary:
At E:\ARUN\TestScript\AutomateScheduledTask.ps1:33 char:4
+    Register-ScheduledTask -Action $action -Trigger $trigger -TaskPath ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTask], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041319,Register-ScheduledTask

我尝试将-Compatibility V1添加到New-ScheduledTaskSettingsSet,但是没有用。

1 个答案:

答案 0 :(得分:0)

Application.put_env/3

通过链接stackoverflow answer(2)获得了此脚本,并对其进行了修改,作为解决方法