pf-WinTaskScheduler.ps1

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
87
88
89
function Get-ScheduledTaskService { 
    $service = New-Object -com 'schedule.service'
    $service.Connect()
    return $service
}

function New-TaskScheduler_Folder ($path) {
    $service = Get-ScheduledTaskService 
    $rootFolder = $service.GetFolder("\") 

    $currentFolder = $rootFolder
    $pathParts = $path -split '\\'
    foreach ($part in $pathParts) {
        $folders = $currentFolder.GetFolders(0)
        $nextFolder = $folders | Where-Object Name -EQ $part

        if ($nextFolder ) {
            $currentFolder = $nextFolder
            continue
        }
        $currentFolder = $currentFolder.CreateFolder($part)
    }
    return $currentFolder
}
function New-TaskScheduler_Folder:::Example {
    New-TaskScheduler_Folder AA\BB\CC
}

function Get-TaskScheduler($currentFolder, $parentPath) {
    if (-not $service) {
        $service = Get-ScheduledTaskService 
    }
    if (-not $currentFolder) {
        $currentFolder = $service.GetFolder("\") 
    }


    $tasks = $currentFolder.GetTasks(0)

    if ($tasks.Count -gt 0) {
        $tasks | ForEach-Object { $_ }
    }

    $folders = $currentFolder.GetFolders(0)
    
    foreach($folder in $folders) {
        Get-TaskScheduler -currentFolder $folder -parentPath $currentFolder.Path
    }
}
function Get-TaskScheduler:::Example {
    $tasksEnabled = Get-TaskScheduler | Where-Object Path -Like '*CORP*' | Where-Object { $_.Enabled }
    Write-Verbose $tasksEnabled
}

function Disable-TaskScheduler {
    Param ( 
        [Parameter(ValueFromPipeline=$true)]
        $task,
        [ScriptBlock]$whileAction,
        [Switch]$stop
    )
    begin {
        $taskList = @()
    }
    process {
        $taskList += $task
    }
    end {
        $taskListEnabled = $taskList | Where-Object { $_.Enabled } 
        try {
            $taskListEnabled | ForEach-Object { $_.Enabled = $false }
            if ($stop) {
                $taskList | ForEach-Object { $_.Stop(0) }
            }
            if ($whileAction) {
                . $whileAction
            }
        }
        finally {
            if ($whileAction) {
                $taskListEnabled | ForEach-Object { $_.Enabled = $true }
            }
        }
    }
}
function Disable-TaskScheduler_Scope:::Example {
    $tasksEnabled | Disable-TaskScheduler -whileAction { Start-Sleep -Seconds 5  } -stop
}