\

How to run PowersShell script in c#

I will show you how to run a PowerShell script in c#.

The execution method in this article is to call Powershell.exe instead of using System.Management.Automation.

Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//using System.Diagnostics;

/// <summary>
/// Run PowerShell script.
/// </summary>
/// <param name="ps1FilePath">PowerShell Script File Name(*.ps1)</param>
/// <param name="args">List of Arguments</param>
/// <param name="stdOut">Standard Output </param>
/// <param name="stdErr">Standard Error</param>
/// <param name="exitCode">Exit Code</param>
public static void ExecPSProcess(string ps1FilePath, List<PowerShellArgs> args, out string stdOut, out string stdErr, out int exitCode)
{
stdOut = "";
stdErr = "";
exitCode = 0;

try
{
string cmdStr = "";
cmdStr = $"-File {ps1FilePath} ";
foreach(var item in args)
{
cmdStr = cmdStr + $"-{item.argName} {item.argValue}";
}

System.Diagnostics.Process process = new System.Diagnostics.Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo("powershell.exe", cmdStr);

processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;

processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;

process = System.Diagnostics.Process.Start(processStartInfo);
process.WaitForExit();

stdOut = process.StandardOutput.ReadToEnd();
stdErr = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;

process.Close();

}
catch
{
throw;
}
}

The following code creates the command string that follows PowerShell.exe.

-File option specifies the PowerShell script file path.

Loop through args using foreach to create a command string that specifies the arguments.

1
2
3
4
5
6
string cmdStr = "";
cmdStr = $"-File {ps1FilePath} ";
foreach(var item in args)
{
cmdStr = cmdStr + $"-{item.argName} {item.argValue}";
}

Create a process object and specify the command string.

1
2
System.Diagnostics.Process process = new System.Diagnostics.Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo("powershell.exe", cmdStr);

Specifies to hide the window, etc.

Start the process and get standard output, standard error, and exit code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;

processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;

process = System.Diagnostics.Process.Start(processStartInfo);
process.WaitForExit();

stdOut = process.StandardOutput.ReadToEnd();
stdErr = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;

process.Close();

PowerShellArgs Class

Use the following class for the argument passed to the PowerShell script.
In the function explained above, considering that multiple specifications are specified, it is passed as a list type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// <summary>
/// PowerShell Scirpt Arguments Class
/// </summary>
public class PowerShellArgs
{
/// <summary>
/// Argument Name
/// </summary>
/// <value></value>
public string argName {get; set;}

/// <summary>
/// Argument Value
/// </summary>
/// <value></value>
public string argValue {get; set;}
}

How to run

For example, suppose you run a PowerShell script like this:

1
2
3
Param($OpenFileName)

code $OpenFileName

This scirpt opens the file specified by OpenFileNamearguments with Visual Studio Code.

The code to call the ExecPSProcess function is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string ps1FilePath = @"D:\OpenFileWithCode.ps1";
PowerShellArgs args = new PowerShellArgs();
args.argName = "OpenFileName";
args.argValue = @"D:\docs.md";

List<PowerShellArgs> argsList = new List<PowerShellArgs>();
argsList.Add(args);

string stdout = "";
string stderr = "";
int exitCode = 0;

ExecPSProcess(ps1FilePath, argsList, out stdout, out stderr, out exitCode);

Console.WriteLine(exitCode);
Console.WriteLine(stdout);
Console.WriteLine(stderr);

Specify the PowerShell script file path to execute and define the arguments.

Arguments are stored in a list type PowerShellArgs object.

1
2
3
4
5
6
7
string ps1FilePath = @"D:\OpenFileWithCode.ps1";
PowerShellArgs args = new PowerShellArgs();
args.argName = "OpenFileName";
args.argValue = @"D:\docs.md";

List<PowerShellArgs> argsList = new List<PowerShellArgs>();
argsList.Add(args);

Define a variable to get the standard output, standard error, and exit code.

Finally, call ExecPSProcess.

1
2
3
4
5
6
7
8
9
string stdout = "";
string stderr = "";
int exitCode = 0;

ExecPSProcess(ps1FilePath, argsList, out stdout, out stderr, out exitCode);

Console.WriteLine(exitCode);
Console.WriteLine(stdout);
Console.WriteLine(stderr);

コメントシステムを導入しました!コメント頂けると嬉しすぎて、光の速さで返信します(●´ω`●)

ExecNote.app リリースしました!

ExecNoteは、コードが実行できるMarkdownアプリケーションです。Markdownドキュメント内に記載したコードをクリックすると実行ができます。わざわざターミナルを 起動させる必要がありません!無料ですのでもしよければダウンロードをお願いします。

About Me

11年目のシステムエンジニアです。アプリで生活や仕事を改善したい🐱仕事効率化、自動化のアプリ開発が得意です、ご相談ください。 🚀エンタメ系アプリの開発も模索中🐬社内SEや個人アプリ開発者、システムエンジニアになりたい人と繋がりたい🐱