如何使用 Powershell 修改现有计划任务?

Dav*_*eny 8 automation powershell scheduled-task windows-server-2008-r2

我正在开发一些使用 Powershell 更新执行各种应用程序的现有计划任务的发布自动化脚本。在我的脚本中,我可以设置应用程序的路径和工作目录,但它似乎没有将更改保存回任务。

function CreateOrUpdateTaskRunner {
    param (
        [Parameter(Mandatory = $TRUE, Position = 1)][string]$PackageName,
        [Parameter(Mandatory = $TRUE, Position = 2)][Version]$Version,
        [Parameter(Mandatory = $TRUE, Position = 3)][string]$ReleaseDirectory
    )

    $taskScheduler = New-Object -ComObject Schedule.Service
    $taskScheduler.Connect("localhost")
    $taskFolder = $taskScheduler.GetFolder('\')

    foreach ($task in $taskFolder.GetTasks(0)) {

        # Check each action to see if it references the current package
        foreach ($action in $task.Definition.Actions) {

            # Ignore actions that do not execute code (e.g. send email, show message)
            if ($action.Type -ne 0) {
                continue
            }

            # Ignore actions that do not execute the specified task runner
            if ($action.WorkingDirectory -NotMatch $application) {
                continue
            }

            # Find the executable
            $path = Join-Path $ReleaseDirectory -ChildPath $application | Join-Path -ChildPath $Version
            $exe = Get-ChildItem $path -Filter "*.exe" | Select -First 1

            # Update the action with the new working directory and executable
            $action.WorkingDirectory = $exe.DirectoryName
            $action.Path = $exe.FullName
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直无法在文档(https://msdn.microsoft.com/en-us/library/windows/desktop/aa383607(v=vs.85).aspx)中找到明显的保存功能。我是否在这里采取了错误的方法,并且需要处理任务 XML?

小智 2

RegisterTask方法一个您将使用的更新标志。像这样的东西:

# Update the action with the new working directory and executable
$action.WorkingDirectory = $exe.DirectoryName
$action.Path = $exe.FullName

#Update Task
$taskFolder.RegisterTask($task.Name, $task.Definition, 4, "<username>", "<password>", 1, $null)
Run Code Online (Sandbox Code Playgroud)

有关每个参数的详细信息,请参阅 msdn 文章。