2021年3月3日星期三

PowerShell Set Mandatory Property Based on Condition

I need to prompt a user to enter the full path of an executable only if it cannot be found in the system PATH.

I have a parameter block like this:

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

This determines if the executable exists in PATH:

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

I want to set the $oc_cli parameter as mandatory only if $oc_in_path is FALSE.

I have tried

$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  

which throws error Attribute argument must be a constant or a script block

I have also tried

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

How can I set the Mandatory property based on a condition?

https://stackoverflow.com/questions/66467232/powershell-set-mandatory-property-based-on-condition March 04, 2021 at 09:18AM

没有评论:

发表评论