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:
parent
f86db3a4dc
commit
09dd535296
1 changed files with 28 additions and 1 deletions
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue