PowerShell Pipeline step throws an error when using Set-PSDebug -Strict, and $LASTEXITCODE is not defined

This issue is archived. You can view it, but you can't modify it. Learn more

XMLWordPrintable

      The PowerShell command Set-PSDebug -Strict makes PowerShell throw an error if an undefined variable is referenced.

      The $LASTEXITCODE automatic variable returns the exit code of the last external executable that was run in the PowerShell session.  If no external executables have been run, then $LASTEXITCODE does not exist.

      The PowerShell Pipeline step apparently wraps the content of the specified script in some additional code, which checks the $LASTEXITCODE variable.

      If no external executables have been run in the script, and Set-PSDebug -Strict is enabled, then the PowerShell Pipeline step throws an error like this:

      powershell.exe : The variable '$LASTEXITCODE' cannot be retrieved because it has not been set.
       At D:\Jenkins.jenkins\workspace\test-pipeline@tmp\durable-0edceab5\powershellWrapper.ps1:3 char:1
       + & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Comm ...
       + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           + CategoryInfo          : NotSpecified: (The variable '$...s not been set.:String) [], RemoteException
           + FullyQualifiedErrorId : NativeCommandError
        
       At D:\Jenkins.jenkins\workspace\test-pipeline@tmp\durable-0edceab5\powershellScript.ps1:9 char:6
       + exit $LASTEXITCODE;
       
       +      ~~~~~~~~~~~~~
       
           + CategoryInfo          : InvalidOperation: (LASTEXITCODE:String) [], RuntimeException
       
           + FullyQualifiedErrorId : VariableIsUndefined
       
        
       
       The variable '$LASTEXITCODE' cannot be retrieved because it has not been set.
       
       At line:1 char:96
       
       + ... eline@tmp\durable-0edceab5\powershellScript.ps1'; exit $LASTEXITCODE;
       
       +                                                            ~~~~~~~~~~~~~
       
           + CategoryInfo          : InvalidOperation: (LASTEXITCODE:String) [], RuntimeException
       
           + FullyQualifiedErrorId : VariableIsUndefined
       

      Here is a demonstration script:

      node ('master') {
          powershell(label: "test", 
              script: '''
      Set-PSDebug -Strict
      "Either of the commented out lines below will make the error below go away." | Out-Host
      # cmd.exe /c :: Running cmd.exe will make PowerShell define the LASTEXITCODE variable
      # Set-PSDebug -Strict:$false
      "Does the LASTEXITCODE variable exist?" | Out-Host
      Test-Path Variable:LASTEXITCODE
      ''')
      }
      

            Assignee:
            Unassigned
            Reporter:
            Ben Langton
            Archiver:
            Jenkins Service Account

              Created:
              Updated:
              Archived: