Private/Apply-ScheduledTask.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
function Apply-ScheduledTask {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [hashtable]$DefinitionObject
    )
    begin {
        try {
            # Prepare scheduled task args based on definition object
            $scheduledTaskArgs = @{
                TaskName = $DefinitionObject['TaskName']
                TaskPath = $DefinitionObject['TaskPath']
                Trigger = @(
                    $DefinitionObject['Trigger'].GetEnumerator() | % {
                        $args = $_
                        New-ScheduledTaskTrigger @args
                    }
                )
                Action = @(
                    $DefinitionObject['Action'].GetEnumerator() | % {
                        $args = $_
                        New-ScheduledTaskAction @args
                    }
                )
                Settings = $(
                    $args = $DefinitionObject['Settings']
                    New-ScheduledTaskSettingsSet @args
                )
                Principal = $(
                    $args = $DefinitionObject['Principal']
                    New-ScheduledTaskPrincipal @args
                )
            }
        }catch {
            throw
        }
    }process {
        try {
            if (Get-ScheduledTask -TaskPath $DefinitionObject['TaskPath'] -TaskName $DefinitionObject['TaskName'] -ErrorAction SilentlyContinue) {
                Set-ScheduledTask @scheduledTaskArgs
            }else {
                Register-ScheduledTask @scheduledTaskArgs
            }
        }catch {
            throw
        }
    }
}