How to execute powershell script from c# with commandline arguments

I have created sample class to execute powershell script from c#.

Example


using System.Diagnostics;
namespace Helper
{
   public   class Program
    {
       public static void Main()
       {
           ProcessStartInfo startInfo = new ProcessStartInfo();
           startInfo.FileName = @"powershell.exe";
           //provide powershell script full path
           startInfo.Arguments = @"& 'C:\powershell-scripts\call-from-c-sharp.ps1'"; 
           startInfo.RedirectStandardOutput = true;
           startInfo.RedirectStandardError = true;
           startInfo.UseShellExecute = false;
           startInfo.CreateNoWindow = true;
           Process process = new Process();
           process.StartInfo = startInfo;
           // execute script call start process
           process.Start();
           // get output information
           string output = process.StandardOutput.ReadToEnd();
           
           // catch error information
           string errors = process.StandardError.ReadToEnd();           
       }
    }
}

Copy and Try it


You can get outout text from StandardOutput method.
Incase some error occurs in powershell script the you can get StandardError from method