如何将它传递给函数时展开PowerShell的数组 [英] How to expand a PowerShell array when passing it to a function

查看:157
本文介绍了如何将它传递给函数时展开PowerShell的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个PowerShell函数,其中第一个调用第二个。他们都取N参数,其中一人被定义为简单地添加标志和调用其他。这里有例子的定义:

I have two PowerShell functions, the first of which invokes the second. They both take N arguments, and one of them is defined to simply add a flag and invoke the other. Here are example definitions:

function inner
{
  foreach( $arg in $args )
    {
      # do some stuff
    }
}

function outer
{
  inner --flag $args
}

使用将是这个样子:

Usage would look something like this:

inner foo bar baz

或本

outer wibble wobble wubble

的目标是为后者的例子为等同于

The goal is for the latter example to be equivalent to

inner --flag wibble wobble wubble

问题:如这里所界定,后者实际上导致传递给两个参数:第一个是--flag和第二个是包含数组维布勒,摆动和wubble。我要的是来接受四个参数:标记和三个原始参数

The Problem: As defined here, the latter actually results in two arguments being passed to inner: the first is "--flag", and the second is an array containing "wibble", "wobble", and "wubble". What I want is for inner to receive four arguments: the flag and the three original arguments.

所以,我想知道是如何说服PowerShell的将它传递给之前扩大$ args数组内,将它作为N个元素,而不是一个单一的阵列。我相信你可以用泼洒运算符(*字符),为此在Ruby和我pretty一定的PowerShell能做到这一点,但我不记得如何。

So what I'm wondering is how to convince powershell to expand the $args array before passing it to inner, passing it as N elements rather than a single array. I believe you can do this in Ruby with the splatting operator (the * character), and I'm pretty sure PowerShell can do it, but I don't recall how.

推荐答案

有没有一个很好的解决方案,以在PowerShell中V1这个问题。在V2我们增加泼洒(尽管由于各种原因,我们用@代替*为此目的)。这里是什么样子:

There isn't a good solution to this problem in PowerSHell V1. In V2 we added splatting (though for various reasons, we use @ instead of * for this purpose). Here's what it looks like:

PS(STA-ISS)(2)>函数foo($ X,$ Y,$ z){X:$ X Y:$ Y Z:$ Z}

PS (STA-ISS) (2) > function foo ($x,$y,$z) { "x:$x y:$y z:$z" }

PS(STA-ISS)(3)> $ a = 1,2,3

PS (STA-ISS) (3) > $a = 1,2,3

PS(STA-ISS)(4)>富美元,单ARG通过了#

PS (STA-ISS) (4) > foo $a # passed as single arg

X:1 2 3 Y:Z:

x:1 2 3 y: z:

PS(STA-ISS)(5)>富@a#splatted

PS (STA-ISS) (5) > foo @a # splatted

X:1 Y:2 Z:3

x:1 y:2 z:3

这篇关于如何将它传递给函数时展开PowerShell的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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