【问题标题】:Missing an argument for parameter on PS1PS1 上的参数缺少参数
【发布时间】:2020-02-06 00:04:25
【问题描述】:

我试图弄清楚如何抛出异常或将其设置为默认值,一旦我没有在参数上设置任何值?

Function ConnectionStrings {

   param(
    [Parameter(
    Mandatory = $false)]

        [AllowNull()]
        [AllowEmptyString()]
    [string] $region 
   )

   try{

    if (!$regionHash.ContainsKey($region)){
        $regionHash["US"]
    } elseif (!$region) {
        $regionHash["US"]
        #$slave = $regionHash["US"].slave
        #$master =  $regionHash["US"].master
        #$track =  $regionHash["US"].tracking
    } else {
        $regionHash[$region]
        #$slave = $regionHash[$region].slave
        #$master =  $regionHash[$region].master
        #$track =  $regionHash[$region].tracking
    }
   } catch {
       Write-Warning -Message "OOPS!"
   }

 }

一旦我运行命令:ConnectionStrings -region 它应该抛出异常或设置为默认值。

需要您的指导,我刚接触 powershell。

谢谢。

编辑:不设置参数ConnectionStrings -region的值

【问题讨论】:

  • 设置Mandatory = $false
  • @Theo 还是一样。 PS C:\Users\tinga\Documents\DevOps\DBAScripts\Modules> ConnectionStrings -region ConnectionStrings : Missing an argument for parameter 'region'. Specify a parameter of type 'System.String' and try again. At line:1 char:19 + ConnectionStrings -region + ~~~~~~~ + CategoryInfo : InvalidArgument: (:) [ConnectionStrings], ParameterBindingException + FullyQualifiedErrorId : MissingArgument,ConnectionStrings
  • 如果你不发送参数,那么你也不应该在调用中指定参数名称。删除-region
  • @Theo 感谢您的宝贵时间。因此,如果用户忘记了值,则此类问题无法解决。

标签: powershell powershell-2.0 powershell-3.0 powershell-4.0


【解决方案1】:

您不能同时使用Mandatory 和同一参数的默认值。为什么不?如果 Param 具有 Mandatory` 属性,则 cmdlet 将提示用户输入值(如果未提供值)。

如果您想使用默认值,请提供这样的值:

function Verb-Noun
{
    Param
    (
        # Param1 help description        
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]        
        $Param1 = 'default'
    )
   "value of `$param1` is $Param1"
}

如果这样执行

>Verb-Noun -Param1 a
value of $param1 is a

但是如果用户没有为参数提供值,就会使用默认值。

Verb-Noun
value of $param1 is default

现在,如果我们像这样添加Mandatory 属性...


Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true)]   
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]        
        $Param1 = 'default'
    )
#rest of code...

当用户未能为Param1 提供值时,系统会提示用户提供值。没有机会使用默认值。

Verb-Noun 
cmdlet Verb-Noun at command pipeline position 1
Supply values for the following parameters:
Param1: 
#function pauses and won't run until a value is provided

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2020-09-09
    • 2018-02-10
    • 2022-01-16
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多