Powershell 函数、参数和 arg [英] Powershell functions, parameters and arg

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

问题描述

我编写了自己的 powershell func 用于调试,例如:

I write own powershell func for debug like:

function StartDebug {
    param (
        [PARAMETER(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        $FunctionName,
        [PARAMETER(Mandatory = $false)]
        $OtherArg
    )

    try {& $FunctionName $OtherArg} catch {...} finally {...}

并在任何情况下使用它,但在 $FunctionName 之后我需要更多参数.在这种情况下传递许多参数是否现实,因为使用从 0 到 10 arg.我是否必须列出可以在函数参数中的所有参数?喜欢:

and use it everyway, but i need more arg after $FunctionName. is it realistic to pass many arguments in this case bec use from 0 to 10 arg. do I have to list all the arguments that can be in the parameters of the function? like:

function StartDebug {
    param (
        [PARAMETER(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        $FunctionName,
        [PARAMETER(Mandatory = $false)]
        $OtherArg,
        [PARAMETER(Mandatory = $false)]
        $OtherArg1,
        [PARAMETER(Mandatory = $false)]
        $OtherArg2,
        [PARAMETER(Mandatory = $false)]
        $OtherArg3
    )

    try {& $FunctionName $OtherArg OtherArg1 OtherArg2 OtherArg3 } catch {...} finally {...}

但我不在代码中使用位置参数,在代码中使用太多命名参数(~100)

but i dont use positional parameters in code and too many named parameters in code (~100)

对此的任何想法感兴趣.tnx!

Interested in any ideas about this. tnx!

推荐答案

神奇的词是 喷溅.您可以向函数提供包含参数的数组或哈希表.飞溅是用 @VariableName 而不是 $ 编写的:

The magic word is Splatting. You can provide an array or a hashtable containing your arguments to a function. The splatter is written with an @VariableName instead of the $:

function StartDebug {
    param (
        [PARAMETER(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        $FunctionName,
        [PARAMETER(Mandatory = $false)]
        $OtherArg
    )

    try {& $FunctionName @OtherArg    # Watch out for the @ in the OtherArg
    } catch {$_} finally {}
}


$FunctionName = 'Get-ChildItem'

$Splatter = @{
    Path      = 'C:\'
    Filter    = 'Users'
    Directory = $true
}

$Splatter2 = @('c:\')

StartDebug $FunctionName $Splatter

StartDebug $FunctionName $Splatter2

但是,如果您想使用单个项目作为 $OtherArg,您必须将它们作为单个元素数组提供,如 $Splatter2 所示.或者扩展您的函数以自动转换数组中的单个参数,但这取决于您.

However if you want to use single items as $OtherArg you will have to provide them as single element array as can be seen with $Splatter2. Or extend your function to transform single arguments in arrays automatically, but thats up to you.

这篇关于Powershell 函数、参数和 arg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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