DscResources/Carbon_ScheduledTask/Carbon_ScheduledTask.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

& (Join-Path -Path $PSScriptRoot -ChildPath '..\Initialize-CarbonDscResource.ps1' -Resolve)

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateLength(1,238)]
        [Alias('TaskName')]
        [string]
        # The name of the scheduled task to return. Wildcards supported. This must be the *full task name*, i.e. the task's path/location and its name.
        $Name,

        [string]
        # Install the task from this XML.
        $TaskXml,

        [Management.Automation.PSCredential]
        # The principal the task should run as. Use `Principal` parameter to run as a built-in security principal. Required if `Interactive` or `NoPassword` switches are used.
        $TaskCredential,

        [ValidateSet('Present','Absent')]
        [string]
        # If `Present`, the service is installed/updated. If `Absent`, the service is removed.
        $Ensure = 'Present'
    )

    Set-StrictMode -Version 'Latest'

    $resource = @{
                    Name = $Name;
                    TaskXml = '';
                    TaskCredential = $null;
                    Ensure = 'Absent';
                }

    if( (Test-ScheduledTask -Name $Name) )
    {
        $task = Get-ScheduledTask -Name $Name
        $resource.TaskCredential = $task.RunAsUser
        $resource.TaskXml = schtasks.exe /query /xml /tn $Name | Where-Object { $_ }
        $resource.TaskXml = $resource.TaskXml -join ([Environment]::NewLine)
        $resource.Ensure = 'Present'
    }

    return $resource
}


function Set-TargetResource
{
    <#
    .SYNOPSIS
    DSC resource for configuring scheduled tasks.
 
    .DESCRIPTION
    The `Carbon_ScheduledTask` resource configures scheduled tasks using `schtasks.exe` with [Task Scheduler XML](http://msdn.microsoft.com/en-us/library/windows/desktop/aa383609.aspx).
 
    The task is installed when the `Ensure` property is set to `Present`. If the task already exists, and the XML of the current task doesn't match the XML passed in, the task is deleted, and a new task is created in its place. The XML comparison is pretty dumb: it compares the XML document(s) as a giant string, not element by element. This means if your XML doesn't order elements in the same way as `schtasks.exe /query /xml`, then your task will always be deleted and re-created. This may or may not be a problem for you.
 
    `Carbon_ScheduledTask` is new in Carbon 2.0.
 
    .LINK
    Get-ScheduledTask
 
    .LINK
    Install-ScheduledTask
 
    .LINK
    Test-ScheduledTask
 
    .LINK
    Uninstall-ScheduledTask
 
    .LINK
    http://technet.microsoft.com/en-us/library/cc725744.aspx#BKMK_create
     
    .LINK
    http://msdn.microsoft.com/en-us/library/windows/desktop/aa383609.aspx
 
    .EXAMPLE
    >
    Demonstrates how to install a new or update an existing scheduled task that runs as a built-in user. The user's SID should be declared in the task XML file.
 
        Carbon_ScheduledTask InstallScheduledTask
        {
            Name = 'ClearApplicationCache';
            TaskXml = (Get-Content -Path $clearApplicationCacheTaskPath.xml -Raw);
        }
 
    .EXAMPLE
    >
    Demonstrates how to install a new or update an existing scheduled task that runs as a custom user.
 
        Carbon_ScheduledTask InstallScheduledTask
        {
            Name = 'ClearApplicationCache';
            TaskXml = (Get-Content -Path $clearApplicationCacheTaskPath.xml -Raw);
            TaskCredential = (Get-Credential 'runasuser');
        }
 
    .EXAMPLE
    >
    Demonstrates how to remove a scheduled task.
 
        Carbon_ScheduledTask InstallScheduledTask
        {
            Name = 'ClearApplicationCache';
            Ensure = 'Absent';
        }
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateLength(1,238)]
        [Alias('TaskName')]
        [string]
        # The name of the scheduled task to return. Wildcards supported. This must be the *full task name*, i.e. the task's path/location and its name.
        $Name,

        [string]
        # Install the task from this XML.
        $TaskXml,

        [Management.Automation.PSCredential]
        # The identity that should run the task. The default is `SYSTEM`.
        $TaskCredential,

        [ValidateSet('Present','Absent')]
        [string]
        # If `Present`, the service is installed/updated. If `Absent`, the service is removed.
        $Ensure = 'Present'
    )

    Set-StrictMode -Version 'Latest'

    $PSBoundParameters.Remove('Ensure')

    if( $Ensure -eq 'Present' )
    {
        $installParams = @{ }
        if( (Test-ScheduledTask -Name $Name ) )
        {
            Write-Verbose ('[{0}] Re-installing' -f $Name)
            $installParams['Force'] = $true
        }
        else
        {
            Write-Verbose ('[{0}] Installing' -f $Name)
        }
        Install-ScheduledTask @PSBoundParameters @installParams
    }
    else
    {
        Write-Verbose ('[{0}] Uninstalling' -f $Name)
        Uninstall-ScheduledTask -Name $Name
    }

}


function Test-TargetResource
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateLength(1,238)]
        [Alias('TaskName')]
        [string]
        # The name of the scheduled task to return. Wildcards supported. This must be the *full task name*, i.e. the task's path/location and its name.
        $Name,

        [string]
        # Install the task from this XML.
        $TaskXml,

        [Management.Automation.PSCredential]
        # The principal the task should run as. Use `Principal` parameter to run as a built-in security principal. Required if `Interactive` or `NoPassword` switches are used.
        $TaskCredential,

        [ValidateSet('Present','Absent')]
        [string]
        # If `Present`, the task is installed/updated. If `Absent`, the task is removed.
        $Ensure = 'Present'
    )

    Set-StrictMode -Version 'Latest'

    $resource = Get-TargetResource -Name $Name

    if( $Ensure -eq 'Present' )
    {
        if( $resource.Ensure -eq 'Absent' )
        {
            Write-Verbose ('[{0}] Desired scheduled task not found' -f $Name)
            return $false
        }

        if( -not $TaskXml )
        {
            Write-Error ('Property ''TaskXml'' is missing or empty. When creating a scheduled task, the ''TaskXml'' property is required.')
            return $true
        }

        $resourceXml = [xml]$resource.TaskXml
        $currentTaskXml = $resourceXml.OuterXml
        $desiredTaskXml = ([xml]$TaskXml).OuterXml
        if( $currentTaskXml -ne $desiredTaskXml )
        {
            $differsAt = 0
            for( $idx = 0; $idx -lt $desiredTaskXml.Length -and $idx -lt $currentTaskXml.Length; ++$idx )
            {
                $charEqual = $desiredTaskXml[$idx] -eq $currentTaskXml[$idx]

                if( -not $charEqual )
                {
                    $differsAt = $idx
                    break
                }
            }
  
            $nameLength = $Name.Length
            $linePrefix = ' ' * ($nameLength + 2)
            $msgFormat = @'
'@
        
            Write-Verbose ('[{0}] Task XML differs:' -f $Name)
            $startIdx = $differsAt - 35
            if( $startIdx -lt 0 )
            {
                $startIdx = 0
            }

            $shortestLength = $currentTaskXml.Length
            if( $desiredTaskXml.Length -lt $shortestLength )
            {
                $shortestLength = $desiredTaskXml.Length
            }

            $length = 70
            if( $startIdx + $length -ge $shortestLength )
            {
                $length = $shortestLength - $startIdx
            }

            Write-Verbose ('{0} Current {1}' -f $linePrefix,$currentTaskXml.Substring($startIdx,$length))
            Write-Verbose ('{0} Desired {1}' -f $linePrefix,$desiredTaskXml.Substring($startIdx,$length))
            if( $length -eq 70 )
            {
                Write-Verbose ('{0} -----------------------------------^' -f $linePrefix)
            }
            return $false
        }
        else
        {
            Write-Verbose ('[{0}] Task XML unchanged' -f $Name)
        }

        if( $TaskCredential )
        {
            $resourceUserName = $resource.TaskCredential | ForEach-Object { Resolve-IdentityName -Name $_ }
            $desiredUserName = $TaskCredential.UserName | ForEach-Object { Resolve-IdentityName -Name $_ }
            if( $resourceUserName -ne $desiredUserName )
            {
                Write-Verbose ('[{0}] [TaskCredential] {1} != {2}' -f $Name,$resourceUserName,$desiredUserName) -Verbose
                return $false
            }
        }

        return $true
    }
    else
    {
        if( $resource.Ensure -eq 'Present' )
        {
            Write-Verbose ('[{0}] Found' -f $Name)
            return $false
        }

        Write-Verbose ('[{0}] Not found' -f $Name)
        return $true
    }
}

Export-ModuleMember -Function *