1 # Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2014, and others
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3 
4 Set-StrictMode -Version 2.0
5 $ErrorActionPreference = "Stop"
6 
Set-Attr($obj, $name, $value)7 Function Set-Attr($obj, $name, $value)
8 {
9 <#
10     .SYNOPSIS
11     Helper function to set an "attribute" on a psobject instance in PowerShell.
12     This is a convenience to make adding Members to the object easier and
13     slightly more pythonic
14     .EXAMPLE
15     Set-Attr $result "changed" $true
16 #>
17 
18     # If the provided $obj is undefined, define one to be nice
19     If (-not $obj.GetType)
20     {
21         $obj = @{ }
22     }
23 
24     Try
25     {
26         $obj.$name = $value
27     }
28     Catch
29     {
30         $obj | Add-Member -Force -MemberType NoteProperty -Name $name -Value $value
31     }
32 }
33 
Exit-Json($obj)34 Function Exit-Json($obj)
35 {
36 <#
37     .SYNOPSIS
38     Helper function to convert a PowerShell object to JSON and output it, exiting
39     the script
40     .EXAMPLE
41     Exit-Json $result
42 #>
43 
44     # If the provided $obj is undefined, define one to be nice
45     If (-not $obj.GetType)
46     {
47         $obj = @{ }
48     }
49 
50     if (-not $obj.ContainsKey('changed')) {
51         Set-Attr -obj $obj -name "changed" -value $false
52     }
53 
54     Write-Output $obj | ConvertTo-Json -Compress -Depth 99
55     Exit
56 }
57 
Fail-Json($obj, $message = $null)58 Function Fail-Json($obj, $message = $null)
59 {
60 <#
61     .SYNOPSIS
62     Helper function to add the "msg" property and "failed" property, convert the
63     PowerShell Hashtable to JSON and output it, exiting the script
64     .EXAMPLE
65     Fail-Json $result "This is the failure message"
66 #>
67 
68     if ($obj -is [hashtable] -or $obj -is [psobject]) {
69         # Nothing to do
70     } elseif ($obj -is [string] -and $null -eq $message) {
71         # If we weren't given 2 args, and the only arg was a string,
72         # create a new Hashtable and use the arg as the failure message
73         $message = $obj
74         $obj = @{ }
75     } else {
76         # If the first argument is undefined or a different type,
77         # make it a Hashtable
78         $obj = @{ }
79     }
80 
81     # Still using Set-Attr for PSObject compatibility
82     Set-Attr -obj $obj -name "msg" -value $message
83     Set-Attr -obj $obj -name "failed" -value $true
84 
85     if (-not $obj.ContainsKey('changed')) {
86         Set-Attr -obj $obj -name "changed" -value $false
87     }
88 
89     Write-Output $obj | ConvertTo-Json -Compress -Depth 99
90     Exit 1
91 }
92 
Add-Warning($obj, $message)93 Function Add-Warning($obj, $message)
94 {
95 <#
96     .SYNOPSIS
97     Helper function to add warnings, even if the warnings attribute was
98     not already set up. This is a convenience for the module developer
99     so they do not have to check for the attribute prior to adding.
100 #>
101 
102     if (-not $obj.ContainsKey("warnings")) {
103         $obj.warnings = @()
104     } elseif ($obj.warnings -isnot [array]) {
105         throw "Add-Warning: warnings attribute is not an array"
106     }
107 
108     $obj.warnings += $message
109 }
110 
Add-DeprecationWarning($obj, $message, $version = $null)111 Function Add-DeprecationWarning($obj, $message, $version = $null)
112 {
113 <#
114     .SYNOPSIS
115     Helper function to add deprecations, even if the deprecations attribute was
116     not already set up. This is a convenience for the module developer
117     so they do not have to check for the attribute prior to adding.
118 #>
119     if (-not $obj.ContainsKey("deprecations")) {
120         $obj.deprecations = @()
121     } elseif ($obj.deprecations -isnot [array]) {
122         throw "Add-DeprecationWarning: deprecations attribute is not a list"
123     }
124 
125     $obj.deprecations += @{
126         msg = $message
127         version = $version
128     }
129 }
130 
Expand-Environment($value)131 Function Expand-Environment($value)
132 {
133 <#
134     .SYNOPSIS
135     Helper function to expand environment variables in values. By default
136     it turns any type to a string, but we ensure $null remains $null.
137 #>
138     if ($null -ne $value) {
139         [System.Environment]::ExpandEnvironmentVariables($value)
140     } else {
141         $value
142     }
143 }
144 
Get-AnsibleParam($obj, $name, $default = $null, $resultobj = @{}, $failifempty = $false, $emptyattributefailmessage, $ValidateSet, $ValidateSetErrorMessage, $type = $null, $aliases = @()145 Function Get-AnsibleParam($obj, $name, $default = $null, $resultobj = @{}, $failifempty = $false, $emptyattributefailmessage, $ValidateSet, $ValidateSetErrorMessage, $type = $null, $aliases = @())
146 {
147 <#
148     .SYNOPSIS
149     Helper function to get an "attribute" from a psobject instance in PowerShell.
150     This is a convenience to make getting Members from an object easier and
151     slightly more pythonic
152     .EXAMPLE
153     $attr = Get-AnsibleParam $response "code" -default "1"
154     .EXAMPLE
155     Get-AnsibleParam -obj $params -name "State" -default "Present" -ValidateSet "Present","Absent" -resultobj $resultobj -failifempty $true
156     Get-AnsibleParam also supports Parameter validation to save you from coding that manually
157     Note that if you use the failifempty option, you do need to specify resultobject as well.
158 #>
159     # Check if the provided Member $name or aliases exist in $obj and return it or the default.
160     try {
161 
162         $found = $null
163         # First try to find preferred parameter $name
164         $aliases = @($name) + $aliases
165 
166         # Iterate over aliases to find acceptable Member $name
167         foreach ($alias in $aliases) {
168             if ($obj.ContainsKey($alias)) {
169                 $found = $alias
170                 break
171             }
172         }
173 
174         if ($null -eq $found) {
175             throw
176         }
177         $name = $found
178 
179         if ($ValidateSet) {
180 
181             if ($ValidateSet -contains ($obj.$name)) {
182                 $value = $obj.$name
183             } else {
184                 if ($null -eq $ValidateSetErrorMessage) {
185                     #Auto-generated error should be sufficient in most use cases
186                     $ValidateSetErrorMessage = "Get-AnsibleParam: Argument $name needs to be one of $($ValidateSet -join ",") but was $($obj.$name)."
187                 }
188                 Fail-Json -obj $resultobj -message $ValidateSetErrorMessage
189             }
190         } else {
191             $value = $obj.$name
192         }
193     } catch {
194         if ($failifempty -eq $false) {
195             $value = $default
196         } else {
197             if (-not $emptyattributefailmessage) {
198                 $emptyattributefailmessage = "Get-AnsibleParam: Missing required argument: $name"
199             }
200             Fail-Json -obj $resultobj -message $emptyattributefailmessage
201         }
202     }
203 
204     # If $null -eq $value, the parameter was unspecified by the user (deliberately or not)
205     # Please leave $null-values intact, modules need to know if a parameter was specified
206     if ($null -eq $value) {
207         return $null
208     }
209 
210     if ($type -eq "path") {
211         # Expand environment variables on path-type
212         $value = Expand-Environment($value)
213         # Test if a valid path is provided
214         if (-not (Test-Path -IsValid $value)) {
215             $path_invalid = $true
216             # could still be a valid-shaped path with a nonexistent drive letter
217             if ($value -match "^\w:") {
218                 # rewrite path with a valid drive letter and recheck the shape- this might still fail, eg, a nonexistent non-filesystem PS path
219                 if (Test-Path -IsValid $(@(Get-PSDrive -PSProvider Filesystem)[0].Name + $value.Substring(1))) {
220                     $path_invalid = $false
221                 }
222             }
223             if ($path_invalid) {
224                 Fail-Json -obj $resultobj -message "Get-AnsibleParam: Parameter '$name' has an invalid path '$value' specified."
225             }
226         }
227     } elseif ($type -eq "str") {
228         # Convert str types to real Powershell strings
229         $value = $value.ToString()
230     } elseif ($type -eq "bool") {
231         # Convert boolean types to real Powershell booleans
232         $value = $value | ConvertTo-Bool
233     } elseif ($type -eq "int") {
234         # Convert int types to real Powershell integers
235         $value = $value -as [int]
236     } elseif ($type -eq "float") {
237         # Convert float types to real Powershell floats
238         $value = $value -as [float]
239     } elseif ($type -eq "list") {
240         if ($value -is [array]) {
241             # Nothing to do
242         } elseif ($value -is [string]) {
243             # Convert string type to real Powershell array
244             $value = $value.Split(",").Trim()
245         } elseif ($value -is [int]) {
246             $value = @($value)
247         } else {
248             Fail-Json -obj $resultobj -message "Get-AnsibleParam: Parameter '$name' is not a YAML list."
249         }
250         # , is not a typo, forces it to return as a list when it is empty or only has 1 entry
251         return ,$value
252     }
253 
254     return $value
255 }
256 
257 #Alias Get-attr-->Get-AnsibleParam for backwards compat. Only add when needed to ease debugging of scripts
258 If (-not(Get-Alias -Name "Get-attr" -ErrorAction SilentlyContinue))
259 {
260     New-Alias -Name Get-attr -Value Get-AnsibleParam
261 }
262 
ConvertTo-Boolnull263 Function ConvertTo-Bool
264 {
265 <#
266     .SYNOPSIS
267     Helper filter/pipeline function to convert a value to boolean following current
268     Ansible practices
269     .EXAMPLE
270     $is_true = "true" | ConvertTo-Bool
271 #>
272     param(
273         [parameter(valuefrompipeline=$true)]
274         $obj
275     )
276 
277     $boolean_strings = "yes", "on", "1", "true", 1
278     $obj_string = [string]$obj
279 
280     if (($obj -is [boolean] -and $obj) -or $boolean_strings -contains $obj_string.ToLower()) {
281         return $true
282     } else {
283         return $false
284     }
285 }
286 
Parse-Args($arguments, $supports_check_mode = $false)287 Function Parse-Args($arguments, $supports_check_mode = $false)
288 {
289 <#
290     .SYNOPSIS
291     Helper function to parse Ansible JSON arguments from a "file" passed as
292     the single argument to the module.
293     .EXAMPLE
294     $params = Parse-Args $args
295 #>
296     $params = New-Object psobject
297     If ($arguments.Length -gt 0)
298     {
299         $params = Get-Content $arguments[0] | ConvertFrom-Json
300     }
301     Else {
302         $params = $complex_args
303     }
304     $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
305     If ($check_mode -and -not $supports_check_mode)
306     {
307         Exit-Json @{
308             skipped = $true
309             changed = $false
310             msg = "remote module does not support check mode"
311         }
312     }
313     return $params
314 }
315 
316 
Get-FileChecksum($path, $algorithm = '...')317 Function Get-FileChecksum($path, $algorithm = 'sha1')
318 {
319 <#
320     .SYNOPSIS
321     Helper function to calculate a hash of a file in a way which PowerShell 3
322     and above can handle
323 #>
324     If (Test-Path -LiteralPath $path -PathType Leaf)
325     {
326         switch ($algorithm)
327         {
328             'md5' { $sp = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
329             'sha1' { $sp = New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider }
330             'sha256' { $sp = New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider }
331             'sha384' { $sp = New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider }
332             'sha512' { $sp = New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider }
333             default { Fail-Json @{} "Unsupported hash algorithm supplied '$algorithm'" }
334         }
335 
336         If ($PSVersionTable.PSVersion.Major -ge 4) {
337             $raw_hash = Get-FileHash -LiteralPath $path -Algorithm $algorithm
338             $hash = $raw_hash.Hash.ToLower()
339         } Else {
340             $fp = [System.IO.File]::Open($path, [System.IO.Filemode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite);
341             $hash = [System.BitConverter]::ToString($sp.ComputeHash($fp)).Replace("-", "").ToLower();
342             $fp.Dispose();
343         }
344     }
345     ElseIf (Test-Path -LiteralPath $path -PathType Container)
346     {
347         $hash = "3";
348     }
349     Else
350     {
351         $hash = "1";
352     }
353     return $hash
354 }
355 
Get-PendingRebootStatusnull356 Function Get-PendingRebootStatus
357 {
358 <#
359     .SYNOPSIS
360     Check if reboot is required, if so notify CA.
361     Function returns true if computer has a pending reboot
362 #>
363     $featureData = Invoke-CimMethod -EA Ignore -Name GetServerFeature -Namespace root\microsoft\windows\servermanager -Class MSFT_ServerManagerTasks
364     $regData = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" "PendingFileRenameOperations" -EA Ignore
365     $CBSRebootStatus = Get-ChildItem "HKLM:\\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing"  -ErrorAction SilentlyContinue| Where-Object {$_.PSChildName -eq "RebootPending"}
366     if(($featureData -and $featureData.RequiresReboot) -or $regData -or $CBSRebootStatus)
367     {
368         return $True
369     }
370     else
371     {
372         return $False
373     }
374 }
375 
376 # this line must stay at the bottom to ensure all defined module parts are exported
377 Export-ModuleMember -Alias * -Function * -Cmdlet *
378