1

I need to do the following in a PowerShell script:

  • call this command: npm run build
  • return the exit code of the npm run build command from my script to the parent (caller) script
  • print text output of the command npm run build but avoid returning the text from my 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

0

1 Answer 1

2
  • 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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.