运行 使用 powershell 批处理文件的 c# exe

Running a c# exe using a powershell batch file

嘿,我有一个简短的问题要问你们。我有一个我构建的 c# 控制台应用程序,我需要为它创建一个 Powershell 批处理文件 运行。我是 Powershell 的新手,尝试了一些我在网上找到的东西,但无济于事。如果有人可以帮助我解决这个问题,我将非常感激。谢谢!

您还有更多选择:

  1. & your.exe [参数列表]
  2. Start-Process 命令让
  3. 使用 .NET Process class

选项 1 通常是最简单的选项,当您只想调用 .exe 时,您现在已经使用了哪个路径和名称,并且不需要任何特殊的东西(例如 运行 它作为不同的用户等。 )

如果选项 1 不令人满意,请使用选项 2 和 3。选项 3 是要配置的 "hardest",但它为您提供了最大的灵活性和对外部进程的创建和执行的控制。

更新 添加了如何将参数发送到 exe 的示例。例如,我使用的是命令提示符实用程序 (cmd.exe),因为它可以在任何 Win OS) 上找到:

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

所以在你的情况下它可能看起来像:

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

您的程序 class 可以如下所示:

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

    }

}