0

I am searching a downloadable powerhsell module (using nuget) that contains a function like this :

 function Invoke-SafeCommand {
      param (
          [ScriptBlock]$ScriptBlock
      )

      try {
          & $ScriptBlock
      }
      catch {
          Write-Host "An exception is thrown : $_"
          exit 1
      }

      if ($LASTEXITCODE -ne 0) {
          Write-Host "The command return this last exit code : $LASTEXITCODE"
          exit $LASTEXITCODE
      }
  }

The goal is to check last exit code or exception of a called C# Console program. This script powershell is run on an azure devops pipeline, and I want the script to fails if the C# Console program fails. Regards Sybaris

Sybaris
  • 41
  • 5
  • Im not sure how this script relates to running a c# exe? Can you not run the exe via: `$Proc = Start-process MyConsoleApp.exe -wait -passthru $Proc.Exitcode ` – KG-DROID Aug 04 '23 at 09:46
  • The function is designed to exit the enclosing script in the event of failure with a nonzero exit code. Just as inside the function, the caller of the enclosing script can check the [automatic `$LASTEXITCODE` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#lastexitcode) for being nonzero to detect failure. I'm not familiar with Azure DevOps, but in general I'd expect CI/CD environments to do such checks themselves. – mklement0 Aug 04 '23 at 11:50
  • @KG-DROID, as an aside: To synchronously execute console applications in the current console window, call them _directly_ (`c:\path\to\some.exe ...` or `& $exePath ...`). This also allows you to capture their output directly and to later query their exit code via `$LASTEXITCODE`. Do _not_ use `Start-Process` (or the `System.Diagnostics.Process` API it is based on) - see [this answer](https://stackoverflow.com/a/51334633/45375). [GitHub docs issue #6239](https://github.com/MicrosoftDocs/PowerShell-Docs/issues/6239) provides guidance on when use of `Start-Process` is and isn't appropriate. – mklement0 Aug 04 '23 at 11:53

0 Answers0