mirror of
https://github.com/ansible-collections/community.general.git
synced 2024-09-14 20:13:21 +02:00
Get-AnsibleParam
This commit is contained in:
parent
dcb8caf9e8
commit
94cfbe7ee9
1 changed files with 29 additions and 3 deletions
|
@ -101,9 +101,11 @@ Function Fail-Json($obj, $message = $null)
|
|||
# Helper function to get an "attribute" from a psobject instance in powershell.
|
||||
# This is a convenience to make getting Members from an object easier and
|
||||
# slightly more pythonic
|
||||
# Example: $attr = Get-Attr $response "code" -default "1"
|
||||
# Example: $attr = Get-AnsibleParam $response "code" -default "1"
|
||||
#Get-AnsibleParam also supports Parameter validation to save you from coding that manually:
|
||||
#Example: Get-AnsibleParam -obj $params -name "State" -default "Present" -ValidateSet "Present","Absent" -resultobj $resultobj -failifempty $true
|
||||
#Note that if you use the failifempty option, you do need to specify resultobject as well.
|
||||
Function Get-Attr($obj, $name, $default = $null, $resultobj, $failifempty=$false, $emptyattributefailmessage)
|
||||
Function Get-AnsibleParam($obj, $name, $default = $null, $resultobj, $failifempty=$false, $emptyattributefailmessage, $ValidateSet, $ValidateSetErrorMessage)
|
||||
{
|
||||
# Check if the provided Member $name exists in $obj and return it or the default.
|
||||
Try
|
||||
|
@ -112,8 +114,29 @@ Function Get-Attr($obj, $name, $default = $null, $resultobj, $failifempty=$false
|
|||
{
|
||||
throw
|
||||
}
|
||||
|
||||
if ($ValidateSet)
|
||||
{
|
||||
if ($ValidateSet -contains ($obj.$name))
|
||||
{
|
||||
$obj.$name
|
||||
}
|
||||
Else
|
||||
{
|
||||
if ($ValidateSetErrorMessage -eq $null)
|
||||
{
|
||||
#Auto-generated error should be sufficient in most use cases
|
||||
$ValidateSetErrorMessage = "Argument $name needs to be one of $($ValidateSet -join ",") but was $($obj.$name)."
|
||||
}
|
||||
Fail-Json -obj $resultobj -message $ValidateSetErrorMessage
|
||||
}
|
||||
}
|
||||
Else
|
||||
{
|
||||
$obj.$name
|
||||
}
|
||||
|
||||
}
|
||||
Catch
|
||||
{
|
||||
If ($failifempty -eq $false)
|
||||
|
@ -131,6 +154,9 @@ Function Get-Attr($obj, $name, $default = $null, $resultobj, $failifempty=$false
|
|||
}
|
||||
}
|
||||
|
||||
#Alias Get-attr-->Get-AnsibleParam for backwards compat.
|
||||
New-Alias -Name Get-attr -Value Get-AnsibleParam
|
||||
|
||||
# Helper filter/pipeline function to convert a value to boolean following current
|
||||
# Ansible practices
|
||||
# Example: $is_true = "true" | ConvertTo-Bool
|
||||
|
|
Loading…
Reference in a new issue