在我的c#应用程序中有一些按钮,当用户单击这个按钮时,应用程序运行一个powershell脚本。
一个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对象来运行脚本
发布于 2022-04-16 23:13:34
当您调用Powershell.exe时,您可以包含“隐藏的-windowstyle”,而powershell应该在后台运行。
https://stackoverflow.com/questions/50542799
复制相似问题