如何将参数传递给从 C# 执行的 powershell 脚本?

时间:2021-06-09 22:01:32

标签: c# powershell arguments

我有以下 Powershell 脚本:

   param(
    [string] $Source ,
    [string] $Target ,
    [string] $UserId  
)
Set-Location "C:\My folder"
& "C:\Program Files\nodejs\node.exe" "index.js" $Source $Target $UserId

我需要从 C# 应用程序执行它,所以我有这个代码:

var process = new Process();
string parameters = string.Format(" -Source {0} -Target {1} -UserId {2} ", Source, Target, UserName);
process.StartInfo.FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
process.StartInfo.Arguments = "\"&'" + ScriptName + "'\" ";
process.Start();
string s = process.StandardOutput.ReadToEnd();
process.WaitForExit();

这适用于调用我的脚本,但我不知道如何传递变量中的参数。

我已经尝试过使用 Runspace runspace = RunspaceFactory.CreateRunspace();但这种方式不会执行我的脚本。

1 个答案:

答案 0 :(得分:0)

假设您可以使用 C# v6+ 内插字符串,并假设您尝试传递给脚本 ScriptName 的参数存储在变量 SourceTarget 和 {{ 1}}:

UserId