【问题标题】:How to pass parameters to a powershell script executed from C#?如何将参数传递给从 C# 执行的 powershell 脚本?
【发布时间】: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


【解决方案1】:

假设您可以使用 C# v6+ 插值字符串,并假设您尝试传递给脚本 ScriptName 的参数存储在变量 SourceTargetUserId 中:

process.StartInfo.Arguments = $"-File \"{ScriptName}\" \"{Source}\" \"{Target}\" \"{UserId}\"";

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2012-05-05
    • 2014-01-07
    • 1970-01-01
    • 2011-08-01
    • 2020-09-04
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多