How to get SCCM to recognize return codes from Powershell script completion?

I'm using an SCCM 2012 application deployment to install software. The specific install type is scripted installer as SCCM kept failing for exe validation errors. The script is powershell and successfully installs the software even when executed by SCCM.

The problem is that SCCM only sees the return of 0 from the completion from the script. I've tried write-host, return, write-output, and just a line item with the code for a soft reboot. None of them seem to be read by SCCM as the app execution log captures a return of 0.

How do you output return codes from powershell so that SCCM can interpret them?


Solution 1:

There is a known problem with powershell exit codes (see the end of this answer) that can manifest when using powershell installation scripts with SCCM. To workaround the problem, I take two measures:

  1. I always have SCCM invoke a batch file which runs the powershell script by invoking powershell.exe explicitly.
  2. I ensure that every code path in the installation script ends in an explicit call to [System.Environment]::Exit().

With these two measures, I haven't had a problem related to exit codes. That is a huge win because troubleshooting exit codes of installation scripts is a slow process because you have to wait for the SCCM client to invoke your script for each iteration of troubleshooting.

Here is what the batch file and powershell script look like:

Install-Application.bat

powershell.exe .\Install-Application.ps1
exit /b %errorlevel%

Install-Application.ps1

try 
{
    # do a bunch of installation stuff
    if ( $rebootNeeded )
    {
        [System.Environment]::Exit(3010)
    }

    [System.Environment]::Exit(0)
}
catch
{
    [System.Environment]::Exit(1)
}

Why are exit codes unreliable when SCCM invokes powershell scripts directly?

Here is how we know exit codes are unreliable:

  • There is at least one known bug where powershell always returns an exit code of 0 when launched in a certain way.
  • Therefore you can only rely on the exit code of a script if you are sure how it is launched.
  • You can never be very sure exactly how SCCM is launching a powershell script -- particularly across SCCM, Windows, and WMF versions.