5

I need to execute a PowerShell script using C#:

ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.FileName = @"cmd.exe";
startInfo.Arguments = @"powershell -File ""C:\Users\user1\Desktop\power.ps1""";
startInfo.Verb = "runas";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;

Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();

This does not work. How can I fix it?

I have a PowerShell script file and sometimes it will have arguments to pass.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ijas
  • 367
  • 1
  • 3
  • 18

3 Answers3

6

None of the answers here helped me but this answer did and was taken from this blog post so credit to the author Duane Newman.

https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/

Here's the full code that will run a PowerShell script when you create a console app in Visual Studio that will ByPass any restrictions.

Just change the ps1File variable to your needs below.

// Code taken from: https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/
// Author: Duane Newman

using System;
using System.Diagnostics;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

            InstallViaPowerShell();
        }

       public static void InstallViaPowerShell()
        {

            var ps1File = @"C:\Users\stevehero\source\repos\RGB Animated Cursors PowerShell\RGB Animated Cursors\install-scheme.ps1";

            var startInfo = new ProcessStartInfo()
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy ByPass -File \"{ps1File}\"",
                UseShellExecute = false
            };
            Process.Start(startInfo);

        }
    }
}

Ste
  • 1,729
  • 1
  • 17
  • 27
  • That may not be sufficient attribution. See e.g. *[What do we do with answers that are entirely copied and improperly attributed (only a "reference" link or similar is included)?](https://meta.stackoverflow.com/questions/321299/)*. E.g., I think the code should quoted. – Peter Mortensen Jul 23 '23 at 14:18
  • Is that ok? I've added the URL and Autor to the code block. – Ste Jul 23 '23 at 18:08
3

Running .ps1 from C# is a really common thing, with many examples all over the web and videos on Youtube showing how/with examples.

Call a Powershell script from c# code

public static int RunPowershellScript(string ps)
{
int errorLevel;
ProcessStartInfo processInfo;
Process process;

processInfo = new ProcessStartInfo("powershell.exe", "-File " + ps);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;

process = Process.Start(processInfo);
process.WaitForExit();

errorLevel = process.ExitCode;
process.Close();

return errorLevel;
}

As well as see these stackoverflowthreads.

To call a PowerShell script file (example.ps1) from C#

When do we need to set UseShellExecute to True?

postanote
  • 15,138
  • 2
  • 14
  • 25
  • I tried this but i don't get expected output. My shell script contains code for creating a folder. process is executed and exit code got 1. but folder is not created. – Ijas Apr 29 '20 at 07:36
  • @ljas, you need elevated access. Try processInfo.Verb = "runas". Also, there will also be the issue where you the script you run has environment lines \n\r which are not read the right way in powershell....any ideas on how to make powershell read them as new arguments ? – NewBie1234 Jan 08 '21 at 12:45
  • @postanote, the link to many examples all over the web are only good if you don't need elevated access. I've looked all over and as of now, the only way to effectively run powershell as an administrator is by running your code above, with the verb "runas". The only issue is that it will only take one argument that way. – NewBie1234 Jan 08 '21 at 12:49
1

In a modern way, you can use System.Management.Automation 7.2.13.

And with the PowerShell class, you can run a PowerShell command or script like below:

PowerShell.Create().AddScript("get-process").Invoke();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sorosh_sabz
  • 2,356
  • 2
  • 32
  • 53