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