RemoteScheduledTasks.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<#
 .Synopsis
  Starts one or more instances of a scheduled task on a remote computer.
 
 .Description
  The Start-ScheduledTask cmdlet starts a registered background task asynchronously on a remote computer.
 
 .Parameter ScheduledTask
  ScheduleTask Object retrieved from Get-RemoteScheduledTask
 
 .Example
  $Tasks = Get-RemoteScheduledTask -ComputerName "SERVER01" -Credential $(Get-Credential)
  $Tasks[0] | Start-RemoteScheduledTask
#>

Function Start-RemoteScheduledTask {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline, Mandatory = $true)]
        [Microsoft.Management.Infrastructure.CimInstance]$ScheduledTask
    )

    begin {
    }

    process {
        Invoke-Command -ComputerName $ScheduledTask.PSComputerName -ScriptBlock {
            param($ScheduledTask)
            Write-Host "Starting: $($ScheduledTask.TaskName)" -ForegroundColor "Green"
            $ScheduledTask | Start-ScheduledTask
        } -ArgumentList $ScheduledTask
    }
}

<#
 .Synopsis
  Gets the task definition object of a scheduled task that is registered on a remote computer.
 
 .Description
  The Get-RemoteScheduledTask cmdlet gets the task definition object of a scheduled task that is registered on a remote computer.
 
 .Parameter ComputerName
  Name of the remote computer
 
 .Example
  Get-RemoteScheduledTask -ComputerName "SERVER01" -Credential $(Get-Credential)
#>

Function Get-RemoteScheduledTask {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$ComputerName,
        [Parameter(Mandatory = $false)]
        [pscredential]$Credential
    )

    begin {}

    process {
        $Tasks = Invoke-Command -ComputerName $ComputerName -ScriptBlock {
            Get-ScheduledTask | Where-Object { ($_.TaskPath -eq "\") -and ($_.State -Ne "Disabled") }
        }
    }

    end {
        Format-RemoteScheduledTasks $Tasks
        return $Tasks
    }
}

Function Format-RemoteScheduledTasks {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $Tasks
    )
    begin {}

    process {
        ForEach ($Index in $Tasks) {
            Write-Host "$($Tasks.IndexOf($Index)). $($Index.TaskName)"
        }
    }

    end {}
}