Reputation: 21
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?
Upvotes: 0
Views: 188
Reputation: 996
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/
Upvotes: 1