PowerShell中的包装器功能:传递其余参数 [英] Wrapper function in PowerShell: Pass remaining parameters

查看:106
本文介绍了PowerShell中的包装器功能:传递其余参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PowerShell中编写一个包装函数,该函数基本上会评估第一个参数,并根据该参数在计算机上运行程序.然后,应该将包装器函数的所有其余参数传递给运行的程序.

I’m trying to write a wrapper function in PowerShell that basically evaluates the first parameter and based on that runs a program on the computer. All the remaining parameters to the wrapper function should then be passed to the program that is ran as well.

所以它应该看起来像这样:

So it should look something like this:

function test ( [string] $option )
{
    if ( $option -eq 'A' )
    {
        Write-Host $args
    }
    elseif ( $option -eq 'B' )
    {
        . 'C:\Program Files\some\program.exe' $args
    }
}

现在仅添加$args不起作用,那么我该怎么做才能使其起作用?另一种选择可能是使用Invoke-Expression,但是感觉有点像eval,因此我想尽可能避免使用这种方法,此外,我认为这样做会限制我使用仅限字符串的参数,对吗?如果可能的话,我希望对包装的程序/cmdlet具有完全的支持-基本上就像一个动态别名一样.那有可能吗?

Now just adding $args does not work, so what do I have to do to make it work? Another option would probably be using Invoke-Expression, but it feels a bit like eval so I want to avoid if possible, and in addition I think doing it like that would limit me to string-only parameters right? If possible I would want to have the full support for the wrapped program/cmdlet - basically like a dynamic alias. Is that even possible?

推荐答案

您要做的就是这种事情.如果需要将短划线前缀的选项传递给与PowerShell通用参数冲突或导致歧义的可执行文件,则可能会遇到麻烦.但这可能会让您入门.

This sort of does what you ask. You may run into trouble if you need to pass dash-prefixed options to the executable that conflict or cause ambiguity with the PowerShell common parameters. But this may get you started.

function Invoke-MyProgram
{
    [CmdletBinding()]
    Param
    (
        [parameter(mandatory=$true, position=0)][string]$Option,
        [parameter(mandatory=$false, position=1, ValueFromRemainingArguments=$true)]$Remaining
    )

    if ($Option -eq 'A')
    {
        Write-Host $Remaining
    }
    elseif ($Option -eq 'B')
    {
        & 'C:\Program Files\some\program.exe' @Remaining # NOTE: @ not $ (splatting)
    }
}

这篇关于PowerShell中的包装器功能:传递其余参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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