2

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'
3
  • 1
    The question should be what need is there to use Write-Output when this is already implicit for PowerShell. The reason you see them in new lines is because InputObject is decorated with ValueFromRemainingArguments so you're actually passing an array to the cmdlet and the cmdlet is outputting exactly that Commented Jan 5, 2023 at 21:11
  • "$(($results | Measure-Object).Count) rows returned" Commented Jan 5, 2023 at 21:15
  • Rod, I've added additional background information to the answer. Commented Jan 5, 2023 at 21:27

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.