为什么以下 PowerShell 5.1 语句会产生 2 行输出
Write-Output ($results | Measure-Object).Count ' rows returned'
输出
11
rows returned
更多背景:
$results = Get-Service -ComputerName $computers -DisplayName *Transportation* | Where-Object {$_.Status -eq "Running"}
$results | Format-Table -AutoSize
Write-Output ($results | Measure-Object).Count ' rows returned'
最佳答案
鉴于 PowerShell 的隐式输出行为,很少有充分的理由使用
Write-Output
- 请参阅 this answer 的底部部分了解背景信息。
因此,结合您不需要 Measure-Object
的事实要获取对象的计数,您可以简化为以下其中一项,这两种方式都隐式输出结果字符串,默认情况下打印到显示屏:
# Expression
[string] $results.Count + ' rows returned'
# Expandable string.
"$($results.Count) rows returned.
至于你尝试过的:
Write-Output
接受开放式数量的参数,它一个接一个输出这些参数,按原样 - 无论数据类型他们是。
因此,($results | Measure-Object).Count
的计算结果将成为 第一个 输出对象 - 类型为 [int]
- 后跟 [string]
' rows returned'
,并且它们在自己的行上单独打印。
相比之下,Write-Host
将会为您提供所需的显示输出(节省额外的空间),因为它字符串化其所有参数并在上打印同一行,用空格分隔:
# Prints '42 and a half' to the display - does NOT produce *data output*
Write-Host (40 + 2) 'and a half'
但是,请注意 Write-Host
is typically the wrong tool to use ,除非目的是仅写入显示,绕过成功输出流,并利用它将输出发送到其他命令、将其捕获在变量中或将其重定向到一个文件。
参见this answer用于并置 Write-Host
和 Write-Output
。
关于PowerShell 输出不是预期的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75024287/