Reputation: 403
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.
Upvotes: 7
Views: 41649
Reputation: 2293
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);
}
}
}
Upvotes: 14
Reputation: 3003
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();
Upvotes: 7
Reputation: 16116
Running .ps1 from C# is a really common thing, with many examples all over the web and videos on Youtube showing how/with examples.
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.
Upvotes: 5