PowerShell想管道中传递数组


如果一个函数返回了不止一个值,PowerShell会自动将它们包装成一个数组,但是如果你把它通过管道传递给另一个函数,PowerShell又会自动地把它拆成一个个的元素。

如果你想摆脱PowerShell这多管闲事,不想集合被解析成单个元素,而是作为一个整体传递给管道,可以这样做,将你的数组放在另外一个数组中:

#requires -Version 1

function Test-ArrayAsReturnValue1
{
  param($count)

  $array = 1..$count

  return $array
}

function Test-ArrayAsReturnValue2
{
  param($count)

  $array = 1..$count

  return ,$array
}

'Result 1:'
Test-ArrayAsReturnValue1 -count 10 | ForEach-Object -Process {
  $_.GetType().FullName 
}

'Result 2:'
Test-ArrayAsReturnValue2 -count 10 | ForEach-Object -Process {
  $_.GetType().FullName 
}

运行上面的例子,我们发现第一个例子逐个处理了我们产生的结果,而第二个例子即使在循环中接收到的也是一个完整的结果。

 
PS C:\> 

Result 1:
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32
System.Int32

Result 2:
System.Object[]

原文链接:Passing Arrays to Pipeline

本文链接: https://www.pstips.net/passing-arrays-to-pipeline.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注