Friday, 14 October 2016

Require PowerShell Modules to Excute CmdLets in C#

Add the following Powershell library as a reference:
C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0

Import the following libraries in C#:
  • using System.Management.Automation;
  • using System.Management.Automation.Runspaces;


Create a C# method:
public void ExecuteScript(string fileName)
{
     try
     {
         string script = File.ReadAllText(fileName);
         var shell = PowerShell.Create();
         shell.Commands.AddScript(script);
         shell.Invoke();
     }
     catch (Exception) {
         // Exception Handling Code
     }
}


No comments:

Activate Office Permanently

Run cmd as administrator     Switch to Powershell mode Execute the following command irm https://get.activated.win | iex