Mitch
Mitch

Reputation: 118

Running a c# exe using a powershell batch file

Hey I've got a quick question for you guys. I have a c# console app that I built, and I need to create a Powershell batch file to run it. I am brand new to Powershell and have tried a few things that I have found online, but to no avail. If someone could help me out with this I would really appreciate it. Thank you!

Upvotes: 2

Views: 147

Answers (1)

milanio
milanio

Reputation: 4232

You have more options:

  1. & your.exe [argument list]
  2. Start-Process command let
  3. Using .NET Process class

The option 1 is usually the easiest onewhen you just want to call .exe which path & name you already now and you don't need anything special (for example to run it as different user etc.)

Use option 2 & 3 when option 1 is not satisfactory. The option 3 is the "hardest" to configure, but it gives you the maximum flexibility and control over creation and execution of the external process.

Update Added example of how to send parameters to exe. For the example I'm using the command prompt utility (cmd.exe) as it can be found on any Win OS) :

$pathToFile= Read-host "Path to file"
& cmd.exe /C "ECHO This command executed in cmd.exe: pathToFile was $pathToFile"

So in your case it can look like:

$pathToFile= Read-host "Path to file"
& myProgram.exe "$pathToFile"

and your Program class can look like:

class Program
{
    private static string pathToFile;

    static int Main(string[] args)
    {

        if (args.Any()) pathToFile = args[0];
        if (args.Length>1) {Console.Error.WriteLine("Too many parameters");
            return 1;
        }
        while (string.IsNullOrWhiteSpace(pathToFile))
        {
            Console.Write("PathToFile is missing. Please provide PathToFile:");
            pathToFile = Console.ReadLine();
        }
        // And here you do something with PathToFile

    }

}

Upvotes: 1

Related Questions