0

I have a PowerShell script that accepts user inputs as user credentials. It prompts a window asking for a username and password. I want to run this script using C#. How can I do this?

1
  • 3
    We are not clairvoyant. Please copy/paste your code into the question as text. Select the code text and use the {} icon. Please make a MCVE. stackoverflow.com/help/mcve Commented Oct 10, 2018 at 14:29

1 Answer 1

1

You need to add a project reference to the System.Management.Automation assembly* and System.Collections.Objectmodel (for execution output).

You will then need to create a static method for the PowerShell class (Note: PowerShell class implements IDisposable so you need to wrap it in a using block):

using (PowerShell PowerShellInstance = PowerShell.Create())
    {
    }

Use the add script method (PowerShellInstance.AddScript()) to add your script.

From there you can execute your script Synchronously or Asynchronously using .Invoke() and .BeginInvoke() respectfully.

Reference this MSDN Blog here: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

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

Comments

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.