brimur
brimur

Reputation: 5

Copy Base64 encoded powershell script to a batch file

I cant seem to get the base64 code for a script to execute in a batch file. While in the Powershell ISE I can do the following and it works fine...

$script = {200 lines of script here}
$bytes = [System.Text.Encoding]::Unicode.GetBytes($script)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand
[Windows.Forms.Clipboard]::SetText( $encodedCommand )

The code executes and gives me the output I expect and the base64 code is copied to the clipboard.

However if I open up notepad and paste in the code after "powershell.exe -encodedCommand" and try to run it I get an error saying "Cannot process the command because the value specified with -EncodedCommand is not properly encoded. The value must be Base64 encoded."

Any ideas what I am doing wrong?

Btw the encoded text is 32676 characters but the error is thrown after about 8K characters so Im wondering if there is a limitation on the size of base64 code that is accepted.

My reason for doing this is to run the script in a batch file without having to call a ps1 file and without having to put the whole script on one line, making it impossible to read. I know I would leave out a few commas and start pulling out my hair! :)

Any help appreciated.

Thanks B

Upvotes: 0

Views: 2432

Answers (2)

Knuckle-Dragger
Knuckle-Dragger

Reputation: 7046

Test the length of $encodedcommand beforehand.

$encodedCommand

$max = 8190

If ($encodedCommand.Length -gt $max) 
{Write-Warning "$encodedCommand.Length is too large to run from cmd.exe."}

Upvotes: 1

MC ND
MC ND

Reputation: 70923

cmd command line is limited to 2047 (xp) or 8191 (vista and later) characters (KB830473)

Upvotes: 3

Related Questions