Why does the following PowerShell 5.1 statement produce output on 2 lines
Write-Output ($results | Measure-Object).Count ' rows returned'
Output
11
rows returned
More context:
$results = Get-Service -ComputerName $computers -DisplayName *Transportation* | Where-Object {$_.Status -eq "Running"}
$results | Format-Table -AutoSize
Write-Output ($results | Measure-Object).Count ' rows returned'
CodePudding user response:
Given PowerShell's implicit output behavior, there's rarely a good reason to use Write-Output
- see the bottom section of this answer for background information.
Thus, combined with the fact that you don't need Measure-Object
to get the count of objects, you can simplify to one of the following, both of which implicitly output the resulting string, which by default prints to the display:
# Expression
[string] $results.Count ' rows returned'
# Expandable string.
"$($results.Count) rows returned.
As for what you tried:
Write-Output
accepts an open-ended number of arguments, which it outputs one by one, as-is - whatever data type they are.
Therefore, what ($results | Measure-Object).Count
evaluates to becomes the first output object - of type [int]
- followed by [string]
' rows returned'
, and they print separately, on their own lines.
By contrast, Write-Host
would have given you the desired display output (save for an extra space), as it stringifies all its arguments and prints on the same line, separated with spaces:
# Prints '42 and a half' to the display - does NOT produce *data output*
Write-Host (40 2) 'and a half'
However, note that Write-Host
is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file.
See this answer for a juxtaposition of Write-Host
and Write-Output
.