Files

81 lines
2.8 KiB
PowerShell
Raw Permalink Normal View History

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Describe "Dynamic parameter support in script cmdlets." -Tags "CI" {
2016-09-15 11:27:44 -07:00
BeforeAll {
Class MyTestParameter {
[parameter(ParameterSetName = 'pset1', position=0, mandatory=1)]
2017-01-16 13:31:14 -08:00
[string] $name
2016-09-15 11:27:44 -07:00
}
2017-01-16 13:31:14 -08:00
2016-09-15 11:27:44 -07:00
function foo-bar
{
[CmdletBinding()]
param($path)
dynamicparam {
if ($PSBoundParameters["path"] -contains "abc") {
$attributes = [System.Management.Automation.ParameterAttribute]::New()
$attributes.ParameterSetName = 'pset1'
$attributes.Mandatory = $false
$attributeCollection = [System.Collections.ObjectModel.Collection``1[System.Attribute]]::new()
$attributeCollection.Add($attributes)
2017-01-16 13:31:14 -08:00
2016-09-15 11:27:44 -07:00
$dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new("dp1", [Int32], $attributeCollection)
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
$paramDictionary.Add("dp1", $dynParam1)
2017-01-16 13:31:14 -08:00
2016-09-15 11:27:44 -07:00
return $paramDictionary
}
elseif($PSBoundParameters["path"] -contains "class") {
$paramDictionary = [MyTestParameter]::new()
return $paramDictionary
}
2017-01-16 13:31:14 -08:00
2016-09-15 11:27:44 -07:00
$paramDictionary = $null
return $null
}
begin {
2017-07-22 05:03:49 +01:00
if(($null -ne $paramDictionary) -and ($paramDictionary -is [MyTestParameter]) ) {
2016-09-15 11:27:44 -07:00
$paramDictionary.name
}
2017-07-22 05:03:49 +01:00
elseif ($null -ne $paramDictionary) {
if ($null -ne $paramDictionary.dp1.Value) {
2016-09-15 11:27:44 -07:00
$paramDictionary.dp1.Value
}
else {
"dynamic parameters not passed"
}
}
else {
"no dynamic parameters"
}
}
process {}
end {}
}
}
It "The dynamic parameter is enabled and bound" {
foo-bar -path abc -dp1 42 | Should -Be 42
2016-09-15 11:27:44 -07:00
}
2017-01-16 13:31:14 -08:00
It "When the dynamic parameter is not available, and raises an error when specified" {
{ foo-bar -path def -dp1 42 } | Should -Throw -ErrorId "NamedParameterNotFound,foo-bar"
2016-09-15 11:27:44 -07:00
}
2017-01-16 13:31:14 -08:00
It "No dynamic parameter shouldn't cause an errr " {
foo-bar -path def | Should -BeExactly 'no dynamic parameters'
2016-09-15 11:27:44 -07:00
}
It "Not specifying dynamic parameter shouldn't cause an error" {
foo-bar -path abc | Should -BeExactly 'dynamic parameters not passed'
2016-09-15 11:27:44 -07:00
}
It "Parameter is defined in Class" {
foo-bar -path class -Name "myName" | Should -BeExactly 'myName'
2016-09-15 11:27:44 -07:00
}
}