Sunday, July 29, 2018

How to execute PowerShell script or cmdlets from C# code?


Sometimes you need to execute PowerShell script or commands from C# code. In this article I’ll explain various methods to execute PowerShell scripts and commands from C# code.

You can execute PowerShell scripts using PowerShell object available in ‘System.Management.Automation’ namespace. This assembly is available in Nuget for download. You can create PowerShell instance and assign script file or command which you would like to execute. You can also get output from PowerShell command after execution and read data from PSObject object.

Let’s have look on below example which executes PowerShell scripts from C# code.

Code –

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;

static void Main(string[] args)
{
    using (PowerShell PowerShellInst = PowerShell.Create())
    {
        string criteria = "system*";
        PowerShellInst.AddScript("Get-Service -DisplayName " + criteria);
        Collection<PSObject> PSOutput = PowerShellInst.Invoke();
        foreach (PSObject obj in PSOutput)
        {
            if (obj != null)
            {
                Console.Write(obj.Properties["Status"].Value.ToString() + " - ");
                Console.WriteLine(obj.Properties["DisplayName"].Value.ToString());
            }
        }
        Console.WriteLine("Done");
        Console.Read();
    }
}

Output –


Now I want to execute below PowerShell script file using C# code.
Code –

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;

static void Main(string[] args)
{
    //Execute PS1 (PowerShell script) file
    using (PowerShell PowerShellInst = PowerShell.Create())
    {
        string path = System.IO.Path.GetDirectoryName(@"C:\Temp\") + "\\Get-EventLog.ps1";
        if (!string.IsNullOrEmpty(path))
            PowerShellInst.AddScript(System.IO.File.ReadAllText(path));

        Collection<PSObject> PSOutput = PowerShellInst.Invoke();
        foreach (PSObject obj in PSOutput)
        {
            if (obj != null)
            {
                Console.Write(obj.Properties["EntryType"].Value.ToString() + " - ");
                Console.Write(obj.Properties["Source"].Value.ToString() + " - ");
                Console.WriteLine(obj.Properties["Message"].Value.ToString() + " - ");
            }
        }
        Console.WriteLine("Done");
        Console.Read();
    }
}

Output –

Command Prompt - You can execute PowerShell scripts and command using PowerShell.exe like below in command prompt.

Similarly you can invoke PowerShell process from C# code and pass command as argument. See below example how execute PowerShell process from code and pass cmdlet as argument.

Code –

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;

static void Main(string[] args)
{
    //execute powershell cmdlets or scripts using command arguments as process
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.FileName = @"powershell.exe";
    //execute powershell script using script file
    //processInfo.Arguments = @"& {c:\temp\Get-EventLog.ps1}";
    //execute powershell command
    processInfo.Arguments = @"& {Get-EventLog -LogName Application -Newest 10 -EntryType Information | Select EntryType, Message}";
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;
    processInfo.UseShellExecute = false;
    processInfo.CreateNoWindow = true;

    //start powershell process using process start info
    Process process = new Process();
    process.StartInfo = processInfo;
    process.Start();

    //read output
    Console.WriteLine("Output - {0}", process.StandardOutput.ReadToEnd());
    //read errors
    Console.WriteLine("Errors - {0}", process.StandardError.ReadToEnd());
    Console.Read();
}

Output –

You can download code from Gist.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –

No comments:

Post a Comment