Link to home
Start Free TrialLog in
Avatar of itnifl
itniflFlag for Norway

asked on

Viewing output from system.diagnostics.process.start in form

I have started a powershell script via system.diagnostics.process.start("script", "arguments"). I want to show the terminal window, or the output in a Visual Basic form or panel. Is this possible, or is it exstensive work?
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

u have 2 options:
1. run the script using System.Diagnostics.Process:
ProcessStartInfo info = new ProcessStartInfo();

            info.FileName = "powershell.exe";
            info.Arguments = @"c:\users\administrator\desktop\getproc_unsigned.ps1";

            Process p =Process.Start(info);
            p.WaitForExit();

in this case the powershell console will display the output of the script (besides the command console).
the drawback here is that u need to sign the script in order to run it, which is a bit of a hussle.
if you will try running it you'll get an error, somthiing like "The execution of scripts is disabled on this system. Please see "Get-Help about_signing" for more details."

to sign a powershell script, do the following:

1. Set up to view the Certificates by running mmc.exe and adding the Certificates snap-in (Choose My User Account in the options dialog)
2. run the following in command console:
makecert -n "CN=PowerShell Local Certificate Root" -a sha1 -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer -ss Root -sr localMachine

3. run the following in command console:
makecert -pe -n "CN=PowerShell User" -ss MY -a sha1 -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

4. make sure execution policy is enable to everyone, by running this:
Set-ExecutionPolicy AllSigned

5. sign the script:
Set-AuthenticodeSignature <script_file_path> @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0]

6. now u can run the script either from console or using Process.Start.

btw, u all the steps i mentioned above can be done using the also by Process.Start, u can generate the certificate once and sign any script u want with the same certificate.

the other option (which is way easier) is to use automation:
u need to add System.Management.Automation to your project, located here:
C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
follow the attched code to run the script and display the output in your console (since the output is a string u can display it wherever u want).
no signing is needed so its really a piece of cake :)






static void Main(string[] args)
        {
            ProcessStartInfo info = new ProcessStartInfo();
 
            Console.WriteLine(RunScript(File.ReadAllText("getproc.ps1")));
 
            Console.Read();
        }
 
        static string RunScript(string scriptText)
        {
            // create Powershell runspace
 
            Runspace runspace = RunspaceFactory.CreateRunspace();
 
            // open it
 
            runspace.Open();
 
            // create a pipeline and feed it the script text
 
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);
 
            // add an extra command to transform the script
            // output objects into nicely formatted strings
 
            // remove this line to get the actual objects
            // that the script returns. For example, the script
 
            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.
 
            pipeline.Commands.Add("Out-String");
 
            // execute the script
 
            Collection<PSObject> results = pipeline.Invoke();
 
            // close the runspace
 
            runspace.Close();
 
            // convert the script result into a single string
 
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
 
            return stringBuilder.ToString();
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of vs_mkazanova
vs_mkazanova

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of itnifl

ASKER

Thanks! I liked your solution the best. The syntax is actually like this:

    Dim proc = New Process
        proc.StartInfo.CreateNoWindow = True
        proc.StartInfo.FileName = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
        proc.StartInfo.Arguments = "D:\Temp\script.ps1"
        proc.StartInfo.RedirectStandardOutput = True
        proc.StartInfo.UseShellExecute = False
        proc.Start()
        Dim output As String = proc.StandardOutput.ReadToEnd()
        proc.WaitForExit()
        pnlScriptList.Controls.Add(dynamicLinks(output, 1, 1))