How do i encode powershell script to base64 UTF16-LE string using C#

1.2k Views Asked by At

I want to encode a powershell script from string, but I can't get it to be encoded in UTF16-LE.

I am using this to encode it to base64 string.

string encodedscript = "powershell -nop -enc " + Convert.ToBase64String(Encoding.UTF8.GetBytes(PowerShellScript));

But when i try to use UTF16-LE encoding, it does not work, for example:

string encodedscript = "powershell -nop -enc " + Convert.ToBase64String(Encoding.UTF16-LE.GetBytes(PowerShellScript));

So my question is how do i encode Powershell script using c# so it will be acceptable by powershell.

I am trying to achieve something like on this website in C#: https://raikia.com/tool-powershell-encoder/

This is code example, the powershell script PowerShellScript is extremly long.

Here is some example encoded script: https://pastesite.org/view/raw/74b98937

Example script: https://pastesite.org/view/raw/b573f289

2

There are 2 best solutions below

2
Speed Runer On BEST ANSWER

Ok thanks everyone, for helping me out, i came out with this batch script which relaunches it self as powershell script, still yet working. But it shows error at start. I am suppressing it with && cls

#^ &@@Echo Off && Cls && Powershell -exec bypass -nop -noni - < "%~f0" && exit /B
#POWERSHELL CODE GOES HERE!
0
Adam Stephenson On

You want to first encode to Unicode then to Base64.

public class Powershell
{
    public static string Command(string command)
    {
        var plainTextBytes = Encoding.Unicode.GetBytes(command);
        var encodedCommand = Convert.ToBase64String(plainTextBytes);

        return $"powershell.exe -EncodedCommand {encodedCommand}";
    }
}