Skip to content

Get-ScheduledTaskInfo

Windows: Retrieves detailed information about scheduled tasks

#Requires -Version 5.1
#Requires -Modules ScheduledTasks

[CmdletBinding()]
Param
(
    [string]$ComputerName = $env:COMPUTERNAME,

    [string]$TaskName = "*",

    [string]$TaskPath = "\",

    [pscredential]$Credential
)

Process
{
    try
    {
        $session = $null
        $taskParams = @{
            'TaskName'    = $TaskName
            '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)
        }

        $tasks = Get-ScheduledTask @taskParams

        $results = foreach ($task in $tasks)
        {
            $info = $task | Get-ScheduledTaskInfo @taskParams -ErrorAction SilentlyContinue
            
            [PSCustomObject]@{
                TaskName     = $task.TaskName
                TaskPath     = $task.TaskPath
                State        = $task.State
                LastRunTime  = if ($info) { $info.LastRunTime } else { "N/A" }
                NextRunTime  = if ($info) { $info.NextRunTime } else { "N/A" }
                LastTaskResult = if ($info) { $info.LastTaskResult } else { 0 }
                Author       = $task.Author
                Action       = ($task.Actions.Execute + " " + $task.Actions.Arguments).Trim()
                ComputerName = $ComputerName
            }
        }

        Write-Output ($results | Sort-Object TaskName)
    }
    catch
    {
        throw
    }
    finally
    {
        if ($null -ne $session)
        {
            Remove-CimSession $session
        }
    }
}

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

Specifies the name of the task to retrieve. Supports wildcards.

Specifies the path in the Task Scheduler hierarchy (e.g., "\Microsoft\Windows\").

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.