如果省略必需的参数,是否可以强制 PowerShell 脚本抛出? [英] Is it possible to force PowerShell script to throw if a required parameter is omitted?

查看:55
本文介绍了如果省略必需的参数,是否可以强制 PowerShell 脚本抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这个脚本中的第二个函数调用抛出一个错误:

I would like the second function call in this script to throw an error:

function Deploy
{

param(

    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$BuildName

    )
    Write-Host "Build name is: $BuildName"

}

Deploy "Build123"

Deploy #Currently prompts for input

提示对于交互式使用脚本非常有用,但这也将由我们的构建服务器执行.

Prompting is great for using the script interactively, but this will also be executed by our build server.

我最好的选择是使用 if 或其他东西做一些自定义验证吗?

Is my best bet just doing some custom validation with an if or something?

推荐答案

一旦参数被标记为必需的,PowerShell 将提示输入值.也就是说,如果您删除了强制属性,那么您可以使用 throw 语句设置一个默认值:

Once the parameter is marked as mandatory PowerShell will prompt for value. That said, if you remove the mandatory attribute then you can set a default value with a throw statement:

function Deploy
{
    param(
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$BuildName=$(throw "BuildName is mandatory, please provide a value.")
    )

    Write-Host "Build name is: $BuildName"
}

这篇关于如果省略必需的参数,是否可以强制 PowerShell 脚本抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆