Share via

PowerShell –EncodedCommand and Round-Trips

PowerShell.exe accepts the –EncodedCommand parameter, which is a way to ‘wrap’ DOS-unfriendly command strings in such a way as to be safely passed into PSH for execution.  It’s a great feature.  However, it has a huge documentation hole.  Let’s see what PowerShell.exe /? has to say about it:

    Accepts a base-64-encoded string version of a command. Use this parameter
    to submit commands to Windows PowerShell that require complex quotation
    marks or curly braces.

And, it has a helpful example:

     # To use the -EncodedCommand parameter:
    $command = 'dir "c:\program files" '
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    powershell.exe -encodedCommand $encodedCommand

That’s pretty useful, right?  Do you see the documentation hole?

It’s missing a way to convert it back. 

“Why would I need a way to convert it back?  It’s encoded, and it’s good, right?”

I’m sure it is.  However, from my SDET (Software Development Engineer in Test) background, I’ve learned not to trust software.  There’s the concept of “round trip” where the data is transformed, then transformed back, and the two instances of data had better be identical.

For purposes of discussion, here’s the reverse process.

 $decodedCommand = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($base64));

“But, PSH hasn’t given us any reason to distrust it, so why go through this trouble?”

Actually, they have.  Any guesses as to which one?


When you round-trip an object through:

 $object | Export-CliXml –Path $path;
$object = Import-CliXml -Path $path;

…you end up with a feature drop: methods. CliXml persists only properties.  Now, I have no idea how to actually persist code functionality, but that’s not my point.  PSH, for all its crunchy goodness, does have areas where round-trip testing shows differences.

However, even if we couldn’t find a difference, software test best practices indicates we should at least evaluate the worthiness of round-trip testing, even if we don’t implement it.