的ForEach-Object
cmdlet的 - 不像foreach
声明 - 本身执行没有枚举。
相反,它对通过管道传递的每个项目进行操作(在接收第一个项目之前以及在接收到最后一个项目之后,还可以选择执行代码)。
因此,可以说是很差命名,因为它是管道提供枚举(默认),并且ForEach-Object
只是调用对于接收到的每个项的脚本块。
下面的例子说明这一点:
# Let the pipeline enumerate the elements of an array:
> 1, 2 | ForEach-Object { "item: [$_]; count: $($_.Count)" }
item: [1]; count: 1
item: [2]; count: 1
# Send the array *as a whole* through the pipeline (PSv4+)
> Write-Output -NoEnumerate 1, 2 | ForEach-Object { "item: [$_]; count: $($_.Count)" }
item: [1 2]; count: 2
注意脚本/功能/ cmdlet的可选择他们写入到输出流(管道)的集合是否应该列举或发送作为一个整体(作为一个单一的对象)。
在PowerShell代码(脚本或功能,无论是先进的(小命令状)与否,枚举是默认的,但你可以Write-Output -NoEnumerate
退出;在-NoEnumerate
开关是PSv4介绍,在此之前,你不得不使用$PSCmdlet.WriteObject()
,这是仅适用于先进脚本/功能。
还要注意,在表达嵌入的命令通过在(...)
力枚举包围它:
# Send array as a whole.
> Write-Output -NoEnumerate 1, 2 | Measure-Object
Count: 1
...
# Converting the Write-Output -NoEnumerate command to an expression
# by enclosing it in in (...) forces enumeration
> (Write-Output -NoEnumerate 1, 2) | Measure-Object
Count: 2
...
快速拨出:'[INT] 1..3'相同'([INT] 1).. 3',这是因为刚'1..3'相同,假设范围运算符表达式的结果是_always_ a(带有[[int]'元素的'[System.Object []]')数组。不管怎么说,像'1'和'3'这样的数字文字都是'[int]'-type,但即使它们不是,PowerShell也会简单地强制它们;例如“1”,“3”将产生相同的结果。 – mklement0