Question

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.

Was it helpful?

Solution

$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

OTHER TIPS

As you cas $Pa and $Pb you can test if they are empty:

You can test with this function :

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

        [Parameter(Mandatory=$False)]
        [string]$pB
       )

  if ($pA -eq [string]::Empty -and $pA -eq [string]::Empty)
  {
    Write-Host "Both are empty"
  }
  elseif ($pA -ne [string]::Empty)
  {
    Write-Host "Pa is not empty"  
  }
  elseif ($pB -ne [string]::Empty)
  {
    Write-Host "Pb is not empty"  
  }
}

Clear-Host
func 

Remains the problem that func -Pa "" will give same results as func But if you just want to test the presence of a parameter you can use the switch attribute.

You can find more about PowerShell scripts and function parameters with these links:

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Parameters

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top