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

当cmdlet缺少参数时,如何让powershell引发异常而不是阻塞,powershell,powershell-5.0,Powershell,Powershell 5.0,假设我有一个cmdlet: function Set-Something { [CmdletBinding()] param( [Parameter(Mandatory)] [string] $SomeValue ) } 以及一些调用我的cmdlet的自动化: Set-Something 这将使powershell会话停止并将其写入屏幕: cmdlet在命令管道位置1设置了某些内容 提供以下参数的值: SomeValue: 在执行自动化

假设我有一个cmdlet:

function Set-Something
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $SomeValue
    )
}
以及一些调用我的cmdlet的自动化:

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

cmdlet在命令管道位置1设置了某些内容 提供以下参数的值: SomeValue:

在执行自动化时,这是非常恼人的:我们真正想要的是powershell不要永远停止,因为它希望用户输入永远不会出现,而只是希望它抛出一个异常“调用中缺少参数以设置某些内容”


这可能吗?

只需删除
[参数(强制)]
部分,并在函数中验证它:

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

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

只需删除
[参数(强制)]
部分,并在函数中验证它:

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

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

在删除
[参数(强制)]
的同时,另一个保留自文档优势的解决方案可能是以非交互方式运行PowerShell

使用
-非交互式
以非交互式模式启动PowerShell。然后您应该会得到一个错误,该错误与
[参数(强制)]
有关

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

在删除
[参数(强制)]
的同时,另一个保留自文档优势的解决方案可能是以非交互方式运行PowerShell

使用
-非交互式
以非交互式模式启动PowerShell。然后您应该会得到一个错误,该错误与
[参数(强制)]
有关

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