[英]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.