在我的c#app中有一些按钮,当用户点击此按钮时,应用程序会运行一个PowerShell脚本。
弹出一个powershell窗口,用户在电源外壳窗口中看到结果。
我正试图从powershell窗口获取输出,并在我的应用程序的某些文本框中显示输出。
这是我的代码:
int ExecuteScript(string path)
{
// this is the script that i would run in a process and would monitor. You don't need to put anything
// in the script just put it to sleep for like 1 minute or so.
string command;
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
command = "$job = [Diagnostics.Process]::Start(\"powershell.exe\", \"" + path + "\")"; // * if $null is passed it needs to be '$null' *
scriptInvoker.Invoke(command);
int pid = 0;
foreach (PSObject result in scriptInvoker.Invoke("$job.id"))
{
if (result != null)
{
pid = Convert.ToInt32(result.ToString());
}
}
return pid;
}
对于某些版本问题,我没有使用PowerShell
对象来运行脚本