1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Make helper functions more robust against undefined powershell objects

This commit is contained in:
Matt Martz 2014-06-19 12:16:43 -05:00
parent f86db3a4dc
commit 09dd535296

View file

@ -46,6 +46,12 @@ Function Parse-Args($arguments)
# Example: Set-Attr $result "changed" $true # Example: Set-Attr $result "changed" $true
Function Set-Attr($obj, $name, $value) 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 $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" # Example: $attr = Get-Attr $response "code" -default "1"
Function Get-Attr($obj, $name, $default = $null) 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) If ($obj.$name.GetType)
{ {
$obj.$name $obj.$name
@ -71,6 +79,12 @@ Function Get-Attr($obj, $name, $default = $null)
# Example: Exit-Json $result # Example: Exit-Json $result
Function Exit-Json($obj) 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 echo $obj | ConvertTo-Json
Exit Exit
} }
@ -78,8 +92,21 @@ Function Exit-Json($obj)
# Helper function to add the "msg" property and "failed" property, convert the # Helper function to add the "msg" property and "failed" property, convert the
# powershell object to JSON and echo it, exiting the script # powershell object to JSON and echo it, exiting the script
# Example: Fail-Json $result "This is the failure message" # 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 "msg" $message
Set-Attr $obj "failed" $true Set-Attr $obj "failed" $true
echo $obj | ConvertTo-Json echo $obj | ConvertTo-Json