c# - 从 C# 项目执行 .ps1 文件作为参数

标签 c# powershell .net-core

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

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 对象执行相同的操作吗?

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

最诚挚的问候,迪米塔

最佳答案

我使用这个辅助方法。

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);

关于c# - 从 C# 项目执行 .ps1 文件作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63613223/

相关文章:

c# - StyleCop SA1402 和泛型

powershell - AWS Powershell - 按名称获取 SNS 主题

powershell - Get-ADGroupMember获取用户详细信息?

python - 通过命令行获取信息提示

c# - WPF Datagrid 多行验证

c# - 服务实例将保持挂起状态,直到在出现错误异常类型初始值设定项后以管理方式恢复或终止

c# - 优雅地杀死在 Linux 上运行的 .NET Core 守护进程

c# - dotnet run --https 的项目问题

c# - 双引号内的双引号

c# - 如何在 .Net Core 中使用自定义预处理器指令