Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a PowerShell script using C#

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.

like image 760
Ijas Avatar asked Apr 15 '26 02:04

Ijas


1 Answers

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);

        }
    }
}

like image 195
Ste Avatar answered Apr 16 '26 16:04

Ste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!