【发布时间】:2021-08-26 22:26:21
【问题描述】:
我有以下 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();但这种方式不会执行我的脚本。
【问题讨论】:
-
您在寻找解决方案的过程中是否发现了这个:stackoverflow.com/questions/10260597/…
-
是的,我尝试了那段代码,但没有成功。只是不要执行我的脚本文件。就像什么都没发生一样……
-
如果我在 CMD 命令行中键入:
C:\windows\system32\windowspowershell\v1.0\powershell.exe -command "get-date -year 2010",则 Powershell 启动并运行get-date -year 2010。尝试类似的东西。即,将参数设置为-command "get-date -year 2010"(替换您的脚本和脚本参数) -
你在哪里声明
ScriptName?另外,参数线不清楚...查看这篇关于如何调用exe的文章:docs.microsoft.com/en-us/powershell/module/… -
哦,当然。我在那段代码之前声明了这个变量。像这样: string ScriptName = "c:\\code\\MyFolder\\data\\script\\StepOne.ps1";而且,我需要 C# 代码来传递参数,而不是 powershell 脚本,因为我已经有了。
标签: c# powershell arguments