简体   繁体   English

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

[英]How to pass parameters to a powershell script executed from C#?

I have the following Powershell script:我有以下 Powershell 脚本:

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

I need to execute it from a C# application, so I have this code:我需要从 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();

This works in invoke my script, but I don't know how to pass the parameters that I have in the variables.这适用于调用我的脚本,但我不知道如何传递变量中的参数。

I already tried using Runspace runspace = RunspaceFactory.CreateRunspace();我已经尝试过使用 Runspace runspace = RunspaceFactory.CreateRunspace(); but this way doesn't execute my script.但这种方式不会执行我的脚本。

Assuming that you can use C# v6+ interpolated strings, and assuming that the arguments you're trying to pass to script ScriptName are stored in variables Source , Target , and UserId :假设您可以使用 C# v6+ 插值字符串,并假设您尝试传递给脚本 ScriptName 的ScriptName存储在变量SourceTargetUserId中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM