Strongly Encouraged Development Guidelines
cmdlet 应该为管道中间实现的 PowerShell ,但我怀疑-Last
对于Select-Object
. 仅仅是因为您无法预先确定最后一个条目。换句话说:您需要等待输入流完成,直到您定义最后一个条目。
为了证明这一点,我写了一个小脚本:
$Data = 1..5 | ForEach-Object {[pscustomobject]@{Index = "$_"}}
$Data | ForEach-Object { Write-Host 'Before' $_.Index; $_ } |
Select-Object -Last 5 | ForEach-Object { Write-Host 'After' $_.Index }
并将其与Select-Object *
:
$Data | ForEach-Object { Write-Host 'Before' $_.Index; $_ } |
Select-Object * | ForEach-Object { Write-Host 'After' $_.Index }
结果(右:Select-Object -Last 5
,左:)Select-Object *
:
-Last 5 *
------- -
Before 1 Before 1
Before 2 After 1
Before 3 Before 2
Before 4 After 2
Before 5 Before 3
After 1 After 3
After 2 Before 4
After 3 After 4
After 4 Before 5
After 5 After 5
尽管没有记录,但我认为我可以从中得出结论,该-Last
参数确实阻塞了管道。
这没什么大不了的,但我也对-First
参数进行了测试,得到了一些令人不安的结果。为了更好地展示这一点,我没有选择所有对象,而只是选择了 ** -First 2**
:
$Data | ForEach-Object { Write-Host 'Before' $_.Index; $_ } |
Select-Object -First 2 | ForEach-Object { Write-Host 'After' $_.Index }
Before 1
After 1
Before 2
After 2
请注意,使用-First 2
参数不仅以下 cmdlet 显示两个对象,而且前面的 cmdlet ( ForEach-Object { Write-Host 'Before' $_.Index; $_ }
) 仅显示 2 个对象(而不是 5 个)。
显然,-First
参数直接引用到先前 cmdlet 的对象,这与使用-Last 2
参数不同:
$Data | ForEach-Object { Write-Host 'Before' $_.Index; $_ } |
Select-Object -Last 2 | ForEach-Object { Write-Host 'After' $_.Index }
Before 1
Before 2
Before 3
Before 4
Before 5
After 4
After 5
Out-Host
使用 cmdlet而不是Write-Host
cmdlet 或将结果发送到变量时也会发生这种情况,例如:
$Before = ""; $After = ""
$Data | ForEach-Object { $Before += $_.Index; $_ } | Select-Object -First 2 | ForEach-Object { $After += $_.Index }
$Before
$After
这显示在 Windows Powershell ( 5.1.18362.628
) 和 PowerShell Core ( 7.0.0
) 上。
这是一个错误吗?