DSCResources/MSFT_xScriptResource/MSFT_xScriptResource.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
data LocalizedData
{
    # culture="en-US"
    ConvertFrom-StringData @'
SetScriptWhatIfMessage=Executing the SetScript with the user supplied credential
InValidResultFromGetScriptError=Failure to get the results from the script in a hash table format.
InValidResultFromTestScriptError=Failure to get a valid result from the execution of TestScript. The Test script should return True or False.
ScriptBlockProviderScriptExecutionFailureError=Failure to successfully execute the script.
GetTargetResourceStartVerboseMessage=Begin executing Get Script.
GetTargetResourceEndVerboseMessage=End executing Get Script.
SetTargetResourceStartVerboseMessage=Begin executing Set Script.
SetTargetResourceEndVerboseMessage=End executing Set Script.
TestTargetResourceStartVerboseMessage=Begin executing Test Script.
TestTargetResourceEndVerboseMessage=End executing Test Script.
ExecutingScriptMessage=Executing Script: {0}
 
'@

}

Import-LocalizedData  LocalizedData -filename MSFT_xScriptResource.strings.psd1

# The Get-TargetResource cmdlet is used to fetch the desired state of the DSC managed node through a powershell script.
# This cmdlet executes the user supplied script (i.e., the script is responsible for validating the desired state of the
# DSC managed node). The result of the script execution is in the form of a hashtable containing all the inormation
# gathered from the GetScript execution.
function Get-TargetResource 
{
    [OutputType([Hashtable])]
    [CmdletBinding()]
     param 
     (         
       [parameter(Mandatory = $true)]
       [ValidateNotNullOrEmpty()]
       [string]
       $GetScript,
  
       [parameter(Mandatory = $true)]
       [ValidateNotNullOrEmpty()]
       [string]$SetScript,

       [parameter(Mandatory = $true)]
       [ValidateNotNullOrEmpty()]
       [string]
       $TestScript,

       [Parameter(Mandatory=$false)]
       [System.Management.Automation.PSCredential] 
       $Credential
     )

    $getTargetResourceResult = $null;

    $getTargetResourceStartVerboseMessage = $($LocalizedData.GetTargetResourceStartVerboseMessage);
    Write-Debug -Message $getTargetResourceStartVerboseMessage;
 
    $script = [ScriptBlock]::Create($GetScript);
    $parameters = $psboundparameters.Remove("GetScript");
    $psboundparameters.Add("ScriptBlock", $script);

    $parameters = $psboundparameters.Remove("SetScript");
    $parameters = $psboundparameters.Remove("TestScript");

    $scriptResult = ScriptExecutionHelper @psboundparameters;
  
    $scriptResultAsErrorRescord = $scriptResult -as [System.Management.Automation.ErrorRecord]
    if($null -ne $scriptResultAsErrorRescord)
    {
        $PSCmdlet.ThrowTerminatingError($scriptResultAsErrorRescord);
    }

    $scriptResultAsHasTable = $scriptResult -as [hashtable]

    if($null -ne $scriptResultAsHasTable)
    {
        $getTargetResourceResult = $scriptResultAsHasTable ;
    }
    else
    {
        # Error message indicating failure to get valid hashtable as the result of the Get script execution.
        $errorId = "InValidResultFromGetScript"; 
        $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult;
        $exception = New-Object System.InvalidOperationException $($LocalizedData.InValidResultFromGetScriptError); 
        $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null

        $PSCmdlet.ThrowTerminatingError($errorRecord);
    }

    $getTargetResourceEndVerboseMessage = $($LocalizedData.GetTargetResourceEndVerboseMessage);
    Write-Debug -Message $getTargetResourceEndVerboseMessage;

    $getTargetResourceResult;
}


# The Set-TargetResource cmdlet is used to Set the desired state of the DSC managed node through a powershell script.
# The method executes the user supplied script (i.e., the script is responsible for validating the desired state of the
# DSC managed node). If the DSC managed node requires a restart either during or after the execution of the SetScript,
# the SetScript notifies the PS Infrasturcure by setting the variable $DSCMachineStatus.IsRestartRequired to $true.
function Set-TargetResource 
{
    [CmdletBinding(SupportsShouldProcess=$true)]
     param 
     (       
       [parameter(Mandatory = $true)]
       [ValidateNotNullOrEmpty()]
       [string]
       $SetScript,

       [parameter(Mandatory = $true)]
       [ValidateNotNullOrEmpty()]
       [string]
       $GetScript,

       [Parameter(Mandatory=$false)]
       [System.Management.Automation.PSCredential] 
       $Credential,

       [parameter(Mandatory = $true)]
       [ValidateNotNullOrEmpty()]
       [string]
       $TestScript

 )

    $setscriptmessage = '$SetScript:' + $SetScript
    $testscriptmessage = '$TestScript:' + $TestScript
    if ($pscmdlet.ShouldProcess($($LocalizedData.SetScriptWhatIfMessage))) 
    {
        $setTargetResourceStartVerboseMessage = $($LocalizedData.SetTargetResourceStartVerboseMessage);
        Write-Debug -Message $setTargetResourceStartVerboseMessage;

        $script = [ScriptBlock]::Create($SetScript);
        $parameters = $psboundparameters.Remove("SetScript");
        $psboundparameters.Add("ScriptBlock", $script);

        $parameters = $psboundparameters.Remove("GetScript");
        $parameters = $psboundparameters.Remove("TestScript");

        $scriptResult = ScriptExecutionHelper @psboundparameters ;

        $scriptResultAsErrorRescord = $scriptResult -as [System.Management.Automation.ErrorRecord]
        if($null -ne $scriptResultAsErrorRescord)
        {
            $PSCmdlet.ThrowTerminatingError($scriptResultAsErrorRescord);
        }
        
        $setTargetResourceEndVerboseMessage = $($LocalizedData.SetTargetResourceEndVerboseMessage);
        Write-Debug -Message $setTargetResourceEndVerboseMessage; 
    }
}


# The Test-TargetResource cmdlet is used to validate the desired state of the DSC managed node through a powershell script.
# The method executes the user supplied script (i.e., the script is responsible for validating the desired state of the
# DSC managed node). The result of the script execution should be true if the DSC managed machine is in the desired state
# or else false should be returned.
function Test-TargetResource 
{
    [OutputType([Boolean])]
    param 
    (       
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $TestScript,
  
        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$SetScript,

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$GetScript,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.PSCredential] 
        $Credential
    )
    $testTargetResourceResult = $false;

    $testTargetResourceStartVerboseMessage = $($LocalizedData.TestTargetResourceStartVerboseMessage);
    Write-Debug -Message $testTargetResourceStartVerboseMessage;

    $script = [ScriptBlock]::Create($TestScript);
    $parameters = $psboundparameters.Remove("TestScript");
    $psboundparameters.Add("ScriptBlock", $script);

    $parameters = $psboundparameters.Remove("GetScript");
    $parameters = $psboundparameters.Remove("SetScript");
     
    $scriptResult = ScriptExecutionHelper @psboundparameters ;

    $scriptResultAsErrorRescord = $scriptResult -as [System.Management.Automation.ErrorRecord]
    if($null -ne $scriptResultAsErrorRescord)
    {
        $PSCmdlet.ThrowTerminatingError($scriptResultAsErrorRescord);
    }

    if($null -eq $scriptResult)
    {
        $errorId = "InValidResultFromTestScript"; 
        $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult;
        $exception = New-Object System.InvalidOperationException $($LocalizedData.InValidResultFromTestScriptError) ;
        $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null

        $PSCmdlet.ThrowTerminatingError($errorRecord);
    }

    # If the script is returing multiple objects, then we consider the last object to be the result of script execution.
    if($scriptResult.GetType().ToString() -eq 'System.Object[]')
    {
        $reultObject = $scriptResult[$scriptResult.Length -1];
    }
    else
    {
        $reultObject = $scriptResult;
    }

    if(($null -ne $reultObject) -and 
       (($reultObject -eq $true) -or ($reultObject -eq $false)))
    {
        $testTargetResourceResult = $reultObject;
    }
    else
    {
        $errorId = "InValidResultFromTestScript"; 
        $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult;
        $exception = New-Object System.InvalidOperationException $($LocalizedData.InValidResultFromTestScriptError) ;
        $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null

        $PSCmdlet.ThrowTerminatingError($errorRecord);
    }

    $testTargetResourceEndVerboseMessage = $($LocalizedData.TestTargetResourceEndVerboseMessage);
    Write-Debug -Message $testTargetResourceEndVerboseMessage;

    $testTargetResourceResult;
}


function ScriptExecutionHelper 
{
    param 
    (
        [ScriptBlock] 
        $ScriptBlock,
    
        [System.Management.Automation.PSCredential] 
        $Credential
    )

    $scriptExecutionResult = $null;

    try
    {

        $executingScriptMessage = $($LocalizedData.ExecutingScriptMessage) -f ${ScriptBlock} ;
        Write-Debug -Message $executingScriptMessage;

       if($null -ne $Credential)
       {
          $scriptExecutionResult = Invoke-Command -ScriptBlock $ScriptBlock -ComputerName . -Credential $Credential
       }
       else
       {
          $scriptExecutionResult = &$ScriptBlock;
       }
        $scriptExecutionResult;
    }
    catch
    {
        # Surfacing the error thrown by the execution of Get/Set/Test script.
        $_;
    }
}

Export-ModuleMember -function Get-TargetResource, Set-TargetResource, Test-TargetResource