hinst
hinst

Reputation: 912

PowerShell redirect output to Write-Host and return exit code

I need to do the following in a PowerShell script:

So far I tried:

@Null = @(npm run build)
return $?

this hides the output completely

Write-Host @(npm run build)
return $?

this prints the output without new lines. Additionally, this prints the output all at once, after npm run build, and not gradually

I have PowerShell Version 7

Upvotes: 1

Views: 1564

Answers (1)

mklement0
mklement0

Reputation: 438323

  • Pipe to Write-Host, or, because it works in a wider range of scenarios, to Out-Host in order to ensure streaming processing (reporting output as it is being received.

    • With external programs, whose output PowerShell only ever interprets as text, Write-Host and Out-Host behave identically with piped input; however, with output from PowerShell-native commands only Out-Host applies the usual, rich output formatting that you would see in the console by default, whereas Write-Host performs simple - and often unhelpful - .ToString() formatting.
  • Use the automatic $LASTEXITCODE variable to obtain the exit code of the most recently executed external program.

    • By contrast, the automatic $? variable is an abstract success indicator, returning either $true or $false, which in the case of external-program calls maps exit code 0 to $true and any nonzero exit code to $false. However, in Windows PowerShell false $false values can occur if a 2> redirection is involved - see this answer.
npm run build | Out-Host
return $LASTEXITCODE

Upvotes: 2

Related Questions