1

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
2
  • There's a good tutorial here: codeproject.com/Articles/18229/… Commented Oct 13, 2015 at 15:17
  • thanks i was reading that page earlier Commented Oct 13, 2015 at 15:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok so i couldn't use any kind of UI with in powershell? i would have to intertwine it with C# gui?
Yeah, I think that's the normal pattern people use. This shows C# capturing the output of a .Invoke() and then outputting it: stackoverflow.com/questions/13251076/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.