user9366827
user9366827

Reputation:

Using C# to pass data to PowerShell

Using Windows 10, I'm making my own C# program to interact with PowerShell scripts. I'm using Quest Active Roles, so this is going to be used across more than one domain. Long story short I want to have a "domain\user" field that a user can type data into. I want that string to then pass to a power shell script that runs things such as:

Set-Qaduser 'domain\user' -Description $null

I want the data put into my C# program to be inserted into the PowerShell script in the correct location where 'domain\user' is currently located.

My first question: How do invoke a PowerShell script to run using the data from the C# program? I have local admin rights and the ability to create and modify any kind of PowerShell script I may need to in order to accomplish this.

My second question: Is something like this even doable? I know I can call on a script to run via C#, but is it even possible to take the input from C# and inject it into a PowerShell script?

Thank you one and all for your time and looking into this. I am a C# newbie, in addition to being a PowerShell newbie. Any and all advice is appreciated. I'm not afraid to read a LOT of text. Please bless me with your knowledge, O Stack Overflow Community.

Upvotes: 0

Views: 300

Answers (1)

Bruce Payette
Bruce Payette

Reputation: 2629

Hosting the PowerShell runtime in your process is probably the most effective solution for you. That way you can pass arbitrary objects to PowerShell commands without worrying about losing fidelity by passing it as a string. Take a look at the Windows PowerShell Host QuickStart and you'll see how easy the API is to use. At the most basic level, you could write something like

   var ps = PowerShell.Create().AddCommand("Get-Process").
            AddParameter("Name", "Notepad*");
    foreach (dynamic proc in ps.Invoke())
    {
        proc.Kill();
    }

which would kill all of your notepad processes :-)

Upvotes: 2

Related Questions