How to decode a PowerShell -EncodedCommand
A PowerShell command line with -EncodedCommand carries the whole script as
one base64 argument:
powershell.exe -NoP -W Hidden -Enc VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIABoAGkA
You find these in process creation logs, scheduled tasks, Run keys, macros and shortcut files. The encoding spares the script any quoting, so it fits on one line, and it keeps the words in the script away from anyone searching command lines for them.
PowerShell takes the parameter under shorter names too. In PowerShell 7.4,
-EncodedCommand, -encodedcommand, -EncodedC, -enc, -en, -ec and -e
all worked. Windows PowerShell’s powershell.exe has the same parameter
(Microsoft’s reference).
What’s inside
The argument is the script’s text in UTF-16LE (what Windows calls “Unicode”),
then base64. UTF-16LE stores each plain ASCII character as its byte and then a
zero byte, which is why encoded commands are full of As. Write-Output hi
becomes:
VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIABoAGkA
The same regularity gives common openings away:
| The script starts with | The base64 starts with |
|---|---|
$ and a letter |
JAB |
IEX |
SQBFAFgA |
iex |
aQBlAHgA |
Decode it
Each of these only decodes the text. Nothing in it runs.
In PowerShell:
$b = 'VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIABoAGkA'
[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b))
In a shell on Linux or macOS:
echo VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIABoAGkA | base64 -d | iconv -f UTF-16LE -t UTF-8
In Python:
import base64
print(base64.b64decode("VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIABoAGkA").decode("utf-16-le"))
All three print Write-Output hi.
Traps
- Decoded as UTF-8, the text has a zero byte after every character
(
W, zero,r, zero,i, zero…). It looks almost right and is easy to misread or to search without a match. - Base64 of UTF-8 isn’t an encoded command. Given
-enc V3JpdGUtT3V0cHV0IGhp(Write-Output hiin UTF-8), PowerShell 7.4 still reads it as UTF-16LE and fails:The term '牗瑩ⵥ畏灴瑵栠…' is not recognized. Characters like those in a decoded command mean the wrong encoding, either yours or the attacker’s. - The decoded script is rarely the end. It is often another wrapper: an
Invoke-Expressionof more base64, a compressed stream, or a download. Decoding the command line is the first layer, not the answer.
Make one
To test a detection rule or a parser, encode a harmless command the same way:
[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('Write-Output hi'))
On this site
Paste the whole command line, with powershell.exe and its options, or a
cmd /c line that starts PowerShell. The result shows the command line as the
first layer, then the script decoded from -EncodedCommand, then a layer for
each Invoke-Expression it finds inside. Nothing is run. To see what the other
wrappers look like, read
How to deobfuscate PowerShell without running it.