function test
{
[CmdletBinding()]
param
(
[Parameter(
Mandatory = $true,
ParameterSetName = "MyArgument"
)]
[ValidateSet("Value1", "Value2")]
[string[]]
$MyArguments
)
foreach ($MyArgument in $MyArguments)
{
switch ($MyArgument)
{
Value1
{
write-host "$parameter used"
}
Value2
{
write-host "$parameter used"
}
}
}
}
test -MyArgument Value1, Value2
How to get the actual argument passed by parameter if we use switch
? I tried to catch it by $MyInvocation.BoundParameters.Values
and $PSCmdlet.MyInvocation.InvocationName
, but failed.
I want to get instead of a variable $parameter Value1
if we call Value1
, and Value2
if we call Value2
, but all approaches receive all values at once.
Thanks in advance.
function test
{
[CmdletBinding()]
param
(
[Parameter(
Mandatory = $true,
ParameterSetName = "MyArgument"
)]
[ValidateSet("Value1", "Value2")]
[string[]]
$MyArguments
)
foreach ($MyArgument in $MyArguments)
{
switch ($MyArgument)
{
Value1
{
write-host "$parameter used"
}
Value2
{
write-host "$parameter used"
}
}
}
}
test -MyArgument Value1, Value2
How to get the actual argument passed by parameter if we use switch
? I tried to catch it by $MyInvocation.BoundParameters.Values
and $PSCmdlet.MyInvocation.InvocationName
, but failed.
I want to get instead of a variable $parameter Value1
if we call Value1
, and Value2
if we call Value2
, but all approaches receive all values at once.
Thanks in advance.
Because you're using a foreach
loop in your function, the current argument can be represented as $MyArgument
, however the item you're switching on is always represented as $_
or $PSItem
in the action script block, so in this case both options are valid:
Write-Host "$MyArgument used"
# or
Write-Host "$_ used"
Something worth noting about switch
in PowerShell is that it can also enumerate collections, so you can also get rid of your loop and this becomes valid code too:
function test {
[CmdletBinding()]
param(
[Parameter(
Mandatory = $true,
ParameterSetName = 'MyArgument'
)]
[ValidateSet('Value1', 'Value2')]
[string[]] $MyArguments
)
switch ($MyArguments) {
Value1 {
Write-Host "$_ used"
}
Value2 {
Write-Host "$_ used"
}
}
}
test -MyArguments Value1, Value2
Relevant docs:
Write-Host "$_ used"
orWrite-Host "$MyArgument used"
? You're switching on$MyArgument
, the value you're switching on can be represented as$_
in the action block of a switch statement. – Santiago Squarzon Commented Jan 2 at 17:28$MyInvocation, Get-Command -Name $MyInvocation.MyCommand, Get-PSCallStack $MyInvocation.BoundParameters.Values, $PSCmdlet.MyInvocation.InvocationName, $ParameterList = (Get-Command -Name $MyInvocation.MyCommand).Parameters, $ParameterList["Variable"].Attributes.ValidValues
– Sanctuary Commented Jan 2 at 17:52