diff --git a/lib/ansible/module_utils/powershell.ps1 b/lib/ansible/module_utils/powershell.ps1 index 919bf19532..5cae79df6b 100644 --- a/lib/ansible/module_utils/powershell.ps1 +++ b/lib/ansible/module_utils/powershell.ps1 @@ -46,6 +46,12 @@ Function Parse-Args($arguments) # Example: Set-Attr $result "changed" $true Function Set-Attr($obj, $name, $value) { + # If the provided $obj is undefined, define one to be nice + If (-not $obj.GetType) + { + $obj = New-Object psobject + } + $obj | Add-Member -Force -MemberType NoteProperty -Name $name -Value $value } @@ -55,6 +61,8 @@ Function Set-Attr($obj, $name, $value) # Example: $attr = Get-Attr $response "code" -default "1" Function Get-Attr($obj, $name, $default = $null) { + # Check if the provided Member $name exists in $obj and return it or the + # default If ($obj.$name.GetType) { $obj.$name @@ -71,6 +79,12 @@ Function Get-Attr($obj, $name, $default = $null) # Example: Exit-Json $result Function Exit-Json($obj) { + # If the provided $obj is undefined, define one to be nice + If (-not $obj.GetType) + { + $obj = New-Object psobject + } + echo $obj | ConvertTo-Json Exit } @@ -78,8 +92,21 @@ Function Exit-Json($obj) # Helper function to add the "msg" property and "failed" property, convert the # powershell object to JSON and echo it, exiting the script # Example: Fail-Json $result "This is the failure message" -Function Fail-Json($obj, $message) +Function Fail-Json($obj, $message = $null) { + # If we weren't given 2 args, and the only arg was a string, create a new + # psobject and use the arg as the failure message + If ($message -eq $null -and $obj.GetType().Name -eq "String") + { + $message = $obj + $obj = New-Object psobject + } + # If the first args is undefined or not an object, make it an object + ElseIf (-not $obj.GetType -or $obj.GetType().Name -ne "PSCustomObject") + { + $obj = New-Object psobject + } + Set-Attr $obj "msg" $message Set-Attr $obj "failed" $true echo $obj | ConvertTo-Json