Skip to content

Start-ScheduledTaskRemote

Windows: Starts an existing scheduled task immediately

#Requires -Version 5.1
#Requires -Modules ScheduledTasks

[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
    [string]$Name,

    [string]$TaskPath = "\",

    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process {
    try {
        $session = $null
        $taskParams = @{
            'TaskName'    = $Name
            'TaskPath'    = $TaskPath
            'ErrorAction' = 'Stop'
        }

        if ($ComputerName -ne $env:COMPUTERNAME) {
            $sessionParams = @{
                'ComputerName' = $ComputerName
            }
            if ($null -ne $Credential) {
                $sessionParams.Add('Credential', $Credential)
            }
            $session = New-CimSession @sessionParams
            $taskParams.Add('CimSession', $session)
        }

        Write-Verbose "Attempting to start scheduled task '$Name' on '$ComputerName'..."
        $task = Get-ScheduledTask @taskParams
        Start-ScheduledTask -InputObject $task @taskParams | Out-Null

        $updatedTask = Get-ScheduledTask @taskParams
        $result = [PSCustomObject]@{
            TaskName     = $updatedTask.TaskName
            State        = $updatedTask.State
            ComputerName = $ComputerName
            Action       = "Started"
            Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $result
    }
    catch {
        throw
    }
    finally {
        if ($null -ne $session) {
            Remove-CimSession $session
        }
    }
}

Specifies the name of the scheduled task to start.

Specifies the path of the task in the Task Scheduler hierarchy. Defaults to the root (\).

Specifies the name of the target computer. Defaults to the local computer.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.