'Capture output from powershell without The PowerShell object
In my c# app there is some button, when the user clicks on this button the app runs a powershell script.
a window of powershell pops out and the user see the results in the power shell window.
I am trying to grab the output from the powershell window and show the output in some textbox from my app.
Here my code:
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;
}
For some version issues I'm not using PowerShell
object to run the script
Solution 1:[1]
When you are calling Powershell.exe you can include "-windowstyle hidden" and powershell should run in the background.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BrettFord1999 |