How to use a default value with parameter sets in PowerShell?

梦想的初衷 提交于 2019-12-23 17:24:02

问题


I have this function

Function Do-ThisOrThat
{
[cmdletbinding()]
param (
    [Parameter(Mandatory = $false, ParameterSetName="First")]
    [string]$FirstParam = "MyFirstParam",

    [Parameter(Mandatory = $false, ParameterSetName="Second")]
    [string]$SecondParam
    )
    Write-Output "Firstparam: $FirstParam. SecondParam $SecondParam"
}

If I call the function like this Do-ThisOrThat I want it to detect that the $FirstParam has a default value and use that. Is it possible? Running it as is only works if I specify a parameter.

e.g. this works: Do-ThisOrThat -FirstParam "Hello"


回答1:


You need to tell PowerShell which of your parameter sets is the default one:

[cmdletbinding(DefaultParameterSetName="First")]

This will allow you to invoke Do-ThisOrThat without any parameters as well as with a -SecondParameter value, and $FirstParam will have its default value in both cases.

Note, however, that based on how your parameter sets are defined, if you do specify an argument, you can't do so positionally - you must use the parameter name (-FirstParam or -SecondParam).




回答2:


This question is a bit ambiguous.

If you want to set the default parameter set, use the DefaultParameterSetName property in the [CmdletBinding()] attribute:

[CmdletBinding(DefaultParameterSetName='First')]

If, on the other hand you want to detect and infer whether $FirstParam has its default value inside the script, you can check which parameter set has been determined and whether FirstParam parameter was specified by the caller, like this:

if($PSCmdlet.ParameterSetName -eq 'First' -and -not $PSBoundParameters.ContainsKey('FirstParam')){ 
  <# $FirstParam has default value #> 
}


来源:https://stackoverflow.com/questions/42931204/how-to-use-a-default-value-with-parameter-sets-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!