core
core

Reputation: 33059

Piping cmd output to variable in PowerShell

I have the following in a PowerShell script:

cmd /c npm run build-release 
$succeeded = $LastExitCode

What I'd like to do is:

  1. Pipe the output of the cmd to a variable so it doesn't write to the host
  2. Only if $succeeded is eq $true, Write-Host the output variable from that the cmd

How can this be done?

Upvotes: 0

Views: 845

Answers (1)

arco444
arco444

Reputation: 22821

Use Invoke-Expression:

$output = Invoke-Expression "cmd /c npm run build-release"
$succeeded = $LastExitCode

if($succeeded -eq 0) {
  write-output $output
}

Upvotes: 1

Related Questions