【问题标题】:Identify which parameter is passed when running a script识别运行脚本时传递的参数
【发布时间】:2014-04-25 07:50:10
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: powershell command-line-arguments


    【解决方案1】:
    $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
    

    【讨论】:

      【解决方案2】:

      当您输入 $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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        • 2011-12-13
        • 1970-01-01
        • 2016-10-25
        • 2016-06-13
        • 1970-01-01
        相关资源
        最近更新 更多