![](/img/trans.png)
[英]How to pass parameters to a powershell script using c# winforms?
[英]How to pass parameters to a powershell script executed from C#?
我有以下 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(); 但这种方式不会执行我的脚本。
假设您可以使用 C# v6+ 插值字符串,并假设您尝试传递给脚本 ScriptName 的ScriptName
存储在变量Source
、 Target
和UserId
中:
process.StartInfo.Arguments = $"-File \"{ScriptName}\" \"{Source}\" \"{Target}\" \"{UserId}\"";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.