0

Hey guys I am newish to C#. I know powershell. I am trying to figure out how to run a powershell script from a c# program. I have below working as a test program for myself. However when i try and put in more complex scripts ones that can include GUI windows that should pop up nothing seems to run. Am i on the right track to figuring this out? I have also noticed that the semi colon after each line was needed to run the script correctly in C#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {


            using (PowerShell PS = PowerShell.Create())
            {
                PS.AddScript("$file = \"C:\\test\\csharp.txt\";"+
                "Set-Content -path $file -value \"testc\";");
                PS.Invoke();
            }



        }//end of main
 }//end of class
}//end of namespace
Peter3
  • 2,549
  • 4
  • 20
  • 40

1 Answers1

0

Only the UI thread can do UI operations. From what I can see, your PS.Invoke() creates its own thread, and I'm not finding anything that would allow you to promote it to the UI thread.

Dustin_00
  • 345
  • 2
  • 8
  • ok so i couldn't use any kind of UI with in powershell? i would have to intertwine it with C# gui? – Peter3 Oct 13 '15 at 15:33
  • Yeah, I think that's the normal pattern people use. This shows C# capturing the output of a .Invoke() and then outputting it: http://stackoverflow.com/questions/13251076/calling-powershell-from-c-sharp – Dustin_00 Oct 13 '15 at 15:50