PowerShell 根据条件设置强制属性

时间:2021-03-04 01:18:43

标签: powershell

如果在系统 PATH 中找不到可执行文件,我需要提示用户输入的完整路径

我有一个这样的参数块:

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)] [string]$oc_cli,
)

这决定了 PATH 中是否存在可执行文件:

$oc_in_path = [bool] (Get-Command "oc.exe" -ErrorAction Ignore)

如果 $oc_cli$oc_in_path,我想将 FALSE 参数设置为强制only

我试过了

$oc_in_path = [bool] (Get-Command "oc.exe" -ErrorAction Ignore)
function example-function {
    param (
        [Parameter(Mandatory=$oc_in_path)] [string]$oc_cli,
    )
    Write-Host "Do stuff"
}

example-function

抛出错误 Attribute argument must be a constant or a script block

我也试过

[CmdletBinding()]
param (
    if (! ( [bool] (Get-Command "oc.exe" -ErrorAction Ignore) )) {
        [Parameter(Mandatory=$true)] [string]$oc_cli
    }
)

如何根据条件设置 Mandatory 属性?

1 个答案:

答案 0 :(得分:1)

尝试以下操作,它依赖于能够通过任意命令指定默认参数值,使用 $(...)subexpression operator

[CmdletBinding()]
param (
  [Parameter()] # in the absence of property values, this is optional.
  [string] $oc_cli = $(
    if ($cmd = Get-Command -ea Ignore oc.exe) { # oc.exe found in $env:PATH
      $cmd.Path
    } else { # prompt user for the location of oc.exe
      do { 
        $userInput = Read-Host 'Specify the path of executable ''oc.exe''' 
      } until ($cmd = (Get-Command -ea Ignore $userInput))
      $cmd.Path 
    } 
  )
)

"`$oc_cli: [$oc_cli]"

注意:

  • 使用 Parameter attributeMandatory 属性,因为它会 - 在没有传递参数的情况下 - 无条件 em> 提示输入参数(参数值)。

  • 上述内容仍会接受一个可能不存在的 $oc_cli 参数如果显式传递;您可以使用 ValidateScript attribute 来防止帽子。

相关问题