确定运行脚本时传递的参数

时间:2014-03-19 07:59:07

标签: powershell command-line-arguments

我有一个接受两个参数的简单代码。参数是可选的。以下是代码。

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

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

运行脚本时我想知道传递了哪个参数。 pApB

2 个答案:

答案 0 :(得分:7)

$MyInvocation.BoundParameters

返回ps自定义字典对(键/值)和所有传递的参数。

这是a.ps1文件的内容:

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

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

运行此脚本会给出:

PS C:\ps> a -pA pAparam

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

然后你可以检查出现了什么键:

[bool]($MyInvocation.BoundParameters.Keys -match 'pa') # or -match 'pb' belong your needs

答案 1 :(得分:1)

当您使用$ Pa和$ Pb时,您可以测试它们是否为空:

您可以使用此功能进行测试:

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 

仍然是func -Pa""将给出与func相同的结果但是如果您只想测试参数的存在,则可以使用switch属性。

您可以通过以下链接找到有关PowerShell脚本和函数参数的更多信息:

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Parameters