0

I'm querying an API in Powershell and can successfully return the expected results in the console with the following command:

$response.rows.name.Split("`n") | Sort-Object | ForEach-Object { Write-Host $_.Substring(0,$_.IndexOf('.')) }

Now I'm trying to output the results to a text file, but am stumbling over the syntax. This is what I'm trying:

$response.rows.name.Split("`n") | Sort-Object | ForEach-Object { Write-Host $_.Substring(0,$_.IndexOf('.')) } | Out-File $results_file

The expected results still show in the console and the text file is generated, but it is empty. Any advice to point me in the right direction is much appreciated.

  • 4
    `Write-Host` writes _directly_ to the host application UI (ie. the console screen buffer) - remove `Write-Host` and it'll work. Use `Tee-Object` if you want it output to file _and_ screen – Mathias R. Jessen Oct 25 '19 at 15:47

1 Answers1

0

Just use Write-Output instead Write-Host.

Here is a good explanation between the two:

PowerShell difference between Write-Host and Write-Output?

Gyula Kokas
  • 141
  • 6