检查函数中是否存在参数 [英] Check for existence of parameter in function

查看:41
本文介绍了检查函数中是否存在参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能如下:

function T
{
    Param
    (
        [switch] $IsValueNameRegularExpression
    )

    ..
}

通常判断一个参数是否存在你会做if ($Param),如果函数被调用为[switch],只会看到这是一个[switch]code>T -IsValueNameRegularExpression:$false 将在 if ($IsValueNameRegularExpression) 上返回 false,即使参数存在 - 即调用者为可选参数指定了一个值.

Normally to determine if a parameter exists you would do if ($Param), only seeing as this is a [switch], if the function is called as T -IsValueNameRegularExpression:$false will return false on if ($IsValueNameRegularExpression), even though the parameter exists - i.e., the caller specified a value to the optional parameter.

如果我将参数类型从 [switch] 更改为 [bool] 显然会发生同样的事情.

If I change the parameter type from [switch] to [bool] the same thing will happen, obviously.

在我的函数代码中,我调用了一些 .NET 方法,这些方法包含我的 [bool]`[switch]` 参数的默认设置,所以除非用户指定了一个值(无论是true 或 false)我不想将它传递给 .NET 方法.

In the code for my function I call some .NET methods which contain a default setting for my [bool]`[switch]` parameters, so unless the user has specified a value (be it true or false) I don't want to pass it to the .NET method.

我可以为参数分配默认值以匹配 .NET 方法的默认值,但这是假设 .NET 方法的默认值永远不会改变,这可能不是真的...

I could assign default values to the parameter to match those of the default value of the .NET method, but that would be assuming that the default value of the .NET method never changes, which might not be true ...

那么,有没有更优雅的方式来做到这一点?

So, is there a more elegant way of doing this?

推荐答案

使用 $PSBoundParameters.ContainsKey() 来检查参数是否存在:

Use $PSBoundParameters.ContainsKey() in order to check for a parameter presence:

function T
{
    Param
    (
        [switch] $IsValueNameRegularExpression
    )

    $PSBoundParameters.ContainsKey('IsValueNameRegularExpression')
}

T
T -IsValueNameRegularExpression
T -IsValueNameRegularExpression:$false

输出:

False
True
True

这篇关于检查函数中是否存在参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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