DSCResources/Grani_ScriptOnOSVersion/Grani_ScriptOnOSVersion.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
300
301
302
303
304
305
306
307
308
309
310
311
#region Initialize

function Initialize {
    try {
        # Enum for Ensure
        Add-Type -TypeDefinition @"
        public enum EnsureType
        {
            Present,
            Absent
        }
"@
 -ErrorAction SilentlyContinue;

    }
    catch {
        if ($_.FullyQualifiedErrorId -match "TYPE_ALREADY_EXISTS") {
            # enough. I know already imported this type. SHOULD NOT ERROR
            return
        }
        throw
    }
}

. Initialize;

#endregion

#region Message Definition

Data VerboseMessages {
    ConvertFrom-StringData -StringData @"
        BeginGetTarget = Check Platform&OSVersion indicate to run script.
"@

}

Data DebugMessages {
    ConvertFrom-StringData -StringData @"
        PlatformCheck = Checking status for Platform. Current : {0}, Desired {1}
        OSVersionCheck = Checking status for OSVersion. Current : {0}, Desired {1}
        TestScriptCheck = Checking status for TestScript. TestScript : {0}
"@

}

Data ErrorMessages {
    ConvertFrom-StringData -StringData @"
        InvalidTestScript = TestScript should return Boolean but detected return value as null with TestScript : {0}
        UnexpectedWhenValue = Unexpected When Parameter value detected : {0}
"@

}

#endregion

#region *-TargetResource

function Get-TargetResource {
    [OutputType([System.Collections.Hashtable])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [System.String]$Key,

        [System.String]$SetScript,

        [System.String]$TestScript,

        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty,

        [parameter(Mandatory = $true)]
        [System.String]$ExecuteOnPlatform,

        [parameter(Mandatory = $true)]
        [System.String]$ExecuteOnVersion,

        [parameter(Mandatory = $true)]
        [ValidateSet("LessThan", "LessThanEqual", "Equal", "NotEqual", "GreaterThan", "GreaterThanEqual")]
        [System.String]$When
    )

    $returnValue = @{
        Key               = $Key
        SetScript         = $SetScript
        TestScript        = $TestScript
        Credential        = New-CimInstance -ClassName MSFT_Credential -Property @{Username = [string]$Credential.UserName; Password = [string]$null} -Namespace root/microsoft/windows/desiredstateconfiguration -ClientOnly
        ExecuteOnPlatform = $ExecuteOnPlatform
        ExecuteOnVersion  = $ExecuteOnVersion
        When              = $When
    }

    Write-Verbose $VerboseMessages.BeginGetTarget;

    try {
        # System.Environment.OSVersion is only for Full.NET CLR.
        # if DSC is implemented in .NET Core, should use System.Runtime.InteropServices.RuntimeInformation.OSDescription instead.
        $currentVersion = [System.Environment]::OSVersion
        $executeOnVersion = [Version]::Parse($ExecuteOnVersion)

        # Platform check
        Write-Debug ($DebugMessages.PlatformCheck -f $currentVersion.Platform, $ExecuteOnPlatform)
        if ($currentVersion.Platform -ne $ExecuteOnPlatform) {
            $returnValue.Ensure = [EnsureType]::Absent
            return $returnValue
        }

        # OSVersion check
        Write-Debug ($DebugMessages.OSVersionCheck -f $currentVersion.Version, $executeOnVersion)
        switch ($When) {
            "LessThan" {
                if (!($currentVersion.Version -lt $executeOnVersion)) {
                    $returnValue.Ensure = [EnsureType]::Absent
                    return $returnValue
                }
            }
            "LessThanEqual" {
                if (!($currentVersion.Version -le $executeOnVersion)) {
                    $returnValue.Ensure = [EnsureType]::Absent
                    return $returnValue
                }
            }
            "Equal" {
                if (!($currentVersion.Version -eq $executeOnVersion)) {
                    $returnValue.Ensure = [EnsureType]::Absent
                    return $returnValue
                }
            }
            "NotEqual" {
                if (!($currentVersion.Version -ne $executeOnVersion)) {
                    $returnValue.Ensure = [EnsureType]::Absent
                    return $returnValue
                }
            }
            "GreaterThan" {
                if (!($currentVersion.Version -gt $executeOnVersion)) {
                    $returnValue.Ensure = [EnsureType]::Absent
                    return $returnValue
                }
            }
            "GreaterThanEqual" {
                if (!($currentVersion.Version -ge $executeOnVersion)) {
                    $returnValue.Ensure = [EnsureType]::Absent
                    return $returnValue
                }
            }
            Default {
                Write-Error ($ErrorMessages.UnexpectedWhenValue -f $_);
            }
        }

        # TestScript Check
        Write-Debug ($DebugMessages.TestScriptCheck -f $TestScript)
        $testValid = ExecuteTestScriptBlock -ScriptBlockString $TestScript -Credential $Credential
        if ($null -eq $testValid) {
            $errorId = "InvalidTestScript"
            $errorMessage = $ErrorMessages.InvalidTestScript -f $TestScript
            ThrowInvalidDataException -ErrorId $errorId -ErrorMessage $errorMessage
        }
        $returnValue.Ensure = if ($testValid) { [EnsureType]::Present } else { [EnsureType]::Absent }
        return $returnValue;
    }
    catch {
        Write-Error $_;
    }
}

function Set-TargetResource {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [System.String]$Key,

        [System.String]$SetScript,

        [System.String]$TestScript,

        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty,

        [parameter(Mandatory = $true)]
        [System.String]$ExecuteOnPlatform,

        [parameter(Mandatory = $true)]
        [System.String]$ExecuteOnVersion,

        [parameter(Mandatory = $true)]
        [ValidateSet("LessThan", "LessThanEqual", "Equal", "NotEqual", "GreaterThan", "GreaterThanEqual")]
        [System.String]$When
    )

    ExecuteScriptBlock -ScriptBlockString $SetScript -Credential $Credential
}


function Test-TargetResource {
    [OutputType([System.Boolean])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [System.String]$Key,

        [System.String]$SetScript,

        [System.String]$TestScript,

        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty,

        [parameter(Mandatory = $true)]
        [System.String]$ExecuteOnPlatform,

        [parameter(Mandatory = $true)]
        [System.String]$ExecuteOnVersion,

        [parameter(Mandatory = $true)]
        [ValidateSet("LessThan", "LessThanEqual", "Equal", "NotEqual", "GreaterThan", "GreaterThanEqual")]
        [System.String]$When
    )

    $param = @{
        Key               = $Key
        SetScript         = $SetScript
        TestScript        = $TestScript
        Credential        = $Credential
        ExecuteOnPlatform = $ExecuteOnPlatform
        ExecuteOnVersion  = $ExecuteOnVersion
        When              = $When
    }

    return (Get-TargetResource @param).Ensure -eq [EnsureType]::Present
}

#endregion

# ScriptBlock Execute Helper
function ExecuteScriptBlock {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $false)]
        [System.String]$ScriptBlockString = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty
    )

    if ($ScriptBlockString -eq [string]::Empty) { return; }

    try {
        $scriptBlock = [ScriptBlock]::Create($ScriptBlockString).GetNewClosure()
        if ($Credential -eq [PSCredential]::Empty) {
            Write-Debug ($debugMessage.ExecuteScriptBlock -f $ScriptBlockString)
            $scriptBlock.Invoke() | Out-String -Stream | Write-Debug
        }
        else {
            Write-Debug ($debugMessage.ExecuteScriptBlockWithCredential -f $ScriptBlockString)
            Invoke-Command -ScriptBlock $scriptBlock -Credential $Credential -ComputerName . | Out-String -Stream | Write-Debug
        }
    }
    catch {
        Write-Debug ($exceptionMessage.ScriptBlockException -f $ScriptBlockString)
        throw $_
    }
}

function ExecuteTestScriptBlock {
    [OutputType([Bool])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $false)]
        [System.String]$ScriptBlockString = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty
    )

    if ($ScriptBlockString -eq [string]::Empty) { return $true; }

    try {
        $scriptBlock = [ScriptBlock]::Create($ScriptBlockString).GetNewClosure()
        if ($Credential -eq [PSCredential]::Empty) {
            Write-Debug ($debugMessage.ExecuteScriptBlock -f $ScriptBlockString)
            return $scriptBlock.Invoke()
        }
        else {
            Write-Debug ($debugMessage.ExecuteScriptBlockWithCredential -f $ScriptBlockString)
            return Invoke-Command -ScriptBlock $scriptBlock -Credential $Credential -ComputerName .
        }
    }
    catch {
        Write-Debug ($exceptionMessage.ScriptBlockException -f $ScriptBlockString)
        throw $_
    }
}

# Exception Helper
function ThrowInvalidDataException {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [System.String]$ErrorId,

        [parameter(Mandatory = $true)]
        [System.String]$ErrorMessage
    )

    $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidData
    $exception = New-Object System.InvalidOperationException $ErrorMessage
    $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $ErrorId, $errorCategory, $null
    throw $errorRecord
}

Export-ModuleMember -Function *-TargetResource