Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify which parameter is passed when running a script

I have a simple code that accepts two parameters. The parameters are optional. Below is the code.

[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.

like image 604
ѕтƒ Avatar asked Jan 10 '23 23:01

ѕтƒ


1 Answers

$MyInvocation.BoundParameters

return a ps custom dictionary pair (key/value) with all passed parameter.

this is the content of a.ps1 file:

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$False)]
   [string]$pA,

   [Parameter(Mandatory=$False)]
   [string]$pB
)
$MyInvocation.BoundParameters

running this script gives:

PS C:\ps> a -pA pAparam

Key                                                         Value
---                                                         -----
pA                                                          pAparam

then you can check what key is present:

[bool]($MyInvocation.BoundParameters.Keys -match 'pa') # or -match 'pb' belong your needs
like image 182
CB. Avatar answered Jan 19 '23 12:01

CB.