Write-Host
, as the name implies, writes to the host, which in a console window is that window's display (screen), bypassing PowerShell's (success) output stream, the latter being what the pipeline operator (|
) and the redirection operator >
operate on.
In PowerShell v5+ only, Write-Host
writes to the information output stream (stream number 6
- see the about_Redirection help topic; by default, that output still goes to the host) and can therefore be redirected - either via 6>
or via *>
- so the catch-all redirection *>&1
, which redirects all streams to the success output stream (1
), can indeed be used to redirect Write-Host
to the success output stream, but not in earlier PowerShell versions - and Windows Server 2012 R2 shipped with PowerShell version 4.
However, in your case there is no good reason to use Write-Host
to begin with: either use Write-Output
- the cmdlet whose purpose is to write to the success output stream (1
) - or, preferably, use PowerShell's implicit output feature, where any output (return value) not captured in a variable, piped or redirected is implicitly written to the success output stream:
# Note how the use of "$($_.Name) : $($_.PercentProcessorTime)"
# *by itself* implicitly causes it to be *output* (written to the pipeline).
Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor" |
Foreach-Object { "$($_.Name) : $($_.PercentProcessorTime)" } > output.txt
Note the absence of $(...)
, the subexpression operator in the command, which isn't needed.
If the specific spacing between the columns isn't important, you can more simply write (since only 2 properties are being select, implicit Format-Table
formatting is applied):
Get-WmiObject -Query "select Name, PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor" |
Select-Object Name, PercentProcessorTime > output.txt
Note: The CIM cmdlets (e.g., Get-CimInstance
) superseded the WMI cmdlets (e.g., Get-WmiObject
) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell [Core] (version 6 and above), where all future effort will go, doesn't even have them anymore. For more information, see this answer.