当缺少 cmdlet 参数时,如何让 powershell 抛出异常而不是阻塞

How to get powershell to throw exception instead of block when missing parameters to cmdlet

假设我有一个 cmdlet:

function Set-Something
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $SomeValue
    )
}

和一些调用我的 cmdlet 的自动化:

Set-Something

这将使 powershell 会话停止并将其写入屏幕:

cmdlet Set-Something at command pipeline position 1 Supply values for the following parameters: SomeValue:

这在进行自动化时非常烦人:我们真正想要的是 powershell 不会永远停止并期待永远不会出现的用户输入,相反我们只是希望它抛出一个异常 "Missing parameter in call to Set-Something".

这可能吗?

只需删除 [Parameter(Mandatory)] 部分并在函数内部验证它:

function Set-Something
{
    [CmdletBinding()]
    param(
        [string] $SomeValue
    )

    if (!$SomeValue)
    {
    throw "Missing parameter in call to Set-Something"
    }
}

虽然删除 [Parameter(Mandatory)] 作为 有效,但另一个将保留自我记录好处的解决方案可能是 运行 PowerShell 非交互。

使用 -Noninteractive 以非交互模式启动 PowerShell。然后你应该得到一个关于 [Parameter(Mandatory)] 的错误。

Set-Something : Cannot process command because of one or more missing mandatory parameters: SomeValue.
At line:1 char:1
+ Set-Something
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Something], ParameterBindingException
    + FullyQualifiedErrorId : MissingMandatoryParameter,Set-Something