Jeffrey Goldman Jeffrey Goldman - 2 months ago 13
C# Question

How to execute arbitrary executable and failed Cake build based on exit code?

How do I in my Cake build script run an arbitrary executable and check for the exit code of that program?
If it doesn’t return a given exit code, then I wish to fail the build.

Answer

This is achieved using the int StartProcess(FilePath fileName) alias.

Example:

int pingLocalResult = StartProcess("ping", "-n 1 127.0.0.1");

if (pingLocalResult != 0)
{
    throw new Exception("Ping 127.0.0.1 failed.");
}

int pingZeroResult = StartProcess("ping", "-n 1 0");
if (pingZeroResult != 0)
{
    throw new Exception("Ping 0 failed.");
}

Will output something like:

C:\> cake .\startprocess.cake

Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

Pinging 0.0.0.0 with 32 bytes of data:
PING: transmit failed. General failure.

Ping statistics for 0.0.0.0:
    Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
Error: Ping 0 failed.
C:\>

Where the throw new Exception("Ping 0 failed."); will break/abort the build.

Comments