Question:
I have a simple code that accepts two parameters. The parameters are optional. Below is the code.
1 2 3 4 5 6 7 8 9 |
[CmdletBinding()] Param( [Parameter(Mandatory=$False)] [string]$pA, [Parameter(Mandatory=$False)] [string]$pB ) |
when running the script I want to know which parameter is passed. pA
or pB
.
Answer:
1 2 |
$MyInvocation.BoundParameters |
return a ps custom dictionary pair (key/value) with all passed parameter.
this is the content of a.ps1 file:
1 2 3 4 5 6 7 8 9 10 |
[CmdletBinding()] Param( [Parameter(Mandatory=$False)] [string]$pA, [Parameter(Mandatory=$False)] [string]$pB ) $MyInvocation.BoundParameters |
running this script gives:
1 2 3 4 5 6 |
PS C:\ps> a -pA pAparam Key Value --- ----- pA pAparam |
then you can check what key is present:
1 2 |
[bool]($MyInvocation.BoundParameters.Keys -match 'pa') # or -match 'pb' belong your needs |