'get npm process exitcode as output in powershell

I'm new to Powershell and want to automate some process by Powershell script. Is there any way to get the status of npm run build, if it fails. Currently, if I'm not adding a condition then it sequencely runs the next commands either its success or fails.

I already added $ErrorActionPreference = "Stop" but it only works for cmdlet.

$exitcode = npm run build
#need exitcode as output to check
if ($exitcode -eq 0) {
   Remove-Item -Path $spaNodeModulePath -Force -Recurse
   mkdir $spaNodeModulePath
   xcopy $libDistPath $spaNodeModulePath /e
   Set-Location $spaPath
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source