首页 > 解决方案 > 从 C# 项目执行 .ps1 文件作为参数

问题描述

我正在尝试.ps1从我的 C# 控制台应用程序执行文件。使用下面提供的代码,您可以看到我正在尝试做什么:

public static void execitePs(string originalString)
{
        using (PowerShell ps = PowerShell.Create())
        {
            // specify the script code to run.
            ps.AddScript(@"C:\PnP\test_script_json.ps1");

            // specify the parameters to pass into the script.
            ps.AddParameter("originalString", originalString);

            // execute the script and await the result.
            var pipelineObjects = ps.Invoke();
            // print the resulting pipeline objects to the console.


            foreach (dynamic item in pipelineObjects)
            {
                Console.WriteLine(item);

            }
        }
}

基本上,我正在尝试提供该AddScript方法的文件路径,如 Microsoft 示例中所述。这应该调用脚本文件并执行它。以下是脚本文件内容:

param ($originalString)

$JSONString = @"
    $originalString
"@


Write-Output HEREEEEEEEE
$cusomObject = ConvertFrom-Json $JSONString

Write-Host $cusomObject.Name

整个过程基本上是以一些 JSON 作为参数并打印属性name

即使 JSON 缺少属性,它也应该将HEREEEEEEEE字符串打印到控制台。

结果我没有得到任何输出,因为pipelineObjects调用脚本后集合为空。

此外,我设法使用以下方法成功执行它:

Process.Start(@"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe", @"-File ""C:\PnP\test_script_json.ps1"" """ + originalString + "");

但使用它不是那么灵活。

有什么想法可以使用该PowerShell对象做同样的事情吗?

任何帮助/想法表示赞赏!

最好的问候, 迪米塔尔

标签: c#powershell.net-core

解决方案


我使用这个辅助方法。

private Process CreateAndStartProcess(string fileName, string arguments)
{
    var startInfo = new ProcessStartInfo
    {
        WindowStyle = ProcessWindowStyle.Normal,
        FileName = fileName,
        WorkingDirectory = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0",
        Arguments = arguments,
        RedirectStandardOutput = true,
        CreateNoWindow = false,
        RedirectStandardError = true,
        UseShellExecute = true
    };

    var process = new Process
    {
        StartInfo = startInfo
    };

    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return process;
}

您可以通过启动它

var arguments = @"-File C:\PnP\test_script_json.ps1" + originalString;
var process = CreateAndStartProcess("powershell.exe", arguments);

推荐阅读