2

I'd like to create a script like this:

static int Main(string[] args)  
{
    if ( !File.Exists( @"E:\Ivara\Cache\TimeCacheLastUpdated.txt" ) )
    {
        return -1;
    }
    return 6;
}

And run it like this and get the error level:

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn\csi.exe" E:\build\CruiseControl\bin\TestLoggingConfigExists.csx

ECHO %ERRORLEVEL%

Derek
  • 7,615
  • 5
  • 33
  • 58

2 Answers2

2

The program you're running will be csi.exe and so %ERRORLEVEL% will reflect the exit code of that program (i.e. zero in case of successful compilation, non-zero otherwise), and not the script that it runs.

Couple of options that come to mind:

  1. Use csc.exe instead to generate an executable application from your script. Run that and capture its exit code.

  2. If for some reason all this needs to happen in one shot, create a small app that takes the script path as input argument, spawns csc.exe to generate executable, run it, and marshal its exit code. (or use an in-memory compilation + execution alternative: https://josephwoodward.co.uk/2016/12/in-memory-c-sharp-compilation-using-roslyn)

Arash Motamedi
  • 9,284
  • 5
  • 34
  • 43
2

Edit 2: much simpler this time

Passing the exit code to Environment.Exit at the end of the script does the job.

static int Main(string[] args)
{
    if ( !File.Exists( @"E:\Ivara\Cache\TimeCacheLastUpdated.txt" ) )
    {
        return -1;
    }
    return 6;
}

// csi.exe normally ignores the exit code from Main, but we can terminate
// the csi.exe process abruptly, and forward the exit code to the caller.
Environment.Exit(Main(Args.ToArray()));
kostasvs
  • 391
  • 4
  • 12