如何在Powershell中组合两个列表的每个元素

时间:2013-02-28 13:28:03

标签: powershell

假设我有两个这样的数组:

$greetings = "hello","hola","namaste"

$names = "jon","jim"

如果我需要这样的输出:

hello jon
hola jon
namaste jon
hello jim
hola jim
namaste jim

我该怎么办?

我试过了:

$greetings | % { $_ + " " + $names}

这只是给我这样的输出:

hello jon jim
hola jon jim
namaste jon jim

2 个答案:

答案 0 :(得分:3)

一行:

$names | % { foreach($greeting in $greetings) { "$greeting $_" }}

答案 1 :(得分:2)

您需要一个嵌套循环:

$greetings = "hello","hola","namaste"

$names = "jon","jim"

Foreach ($name in $names)
 {
  Foreach ($greeting in $greetings)
   {
    "$greeting $name"
   }
 }