1

I would like to execute an encoded powershell-script from a Windows-batch and pass a parameter to it.

Let's take for example the following script:

param (
    $foo
)
Write-Host("Hello World!" + $foo)

When encoding it to base64, the result is:

cABhAHIAYQBtACAAKAANAAoAIAAgACAAIAAkAGYAbwBvAA0ACgApAA0ACgBXAHIAaQB0AGUALQBIAG8AcwB0ACgAIgBIAGUAbABsAG8AIABXAG8AcgBsAGQAIQAiACAAKwAgACQAZgBvAG8AKQA=

I do then create a batch-skript:

@ECHO OFF
powershell.exe -EncodedCommand "cABhAHIAYQBtACAAKAANAAoAIAAgACAAIAAkAGYAbwBvAA0ACgApAA0ACgBXAHIAaQB0AGUALQBIAG8AcwB0ACgAIgBIAGUAbABsAG8AIABXAG8AcgBsAGQAIQAiACAAKwAgACQAZgBvAG8AKQA="

How can I pass a parameter to the powershell to make it output a value for $foo after "Hello World!"?

Due to the circumstances, I cannot create another script-file or anything similar. The whole process should be contained in the BAT-file.

2

Powershell does not support passing arguments to a script that is encrypted natively.

You can however set variables in the .bat file, then in your script retrieve them.

For example:

$command = 'write-host $env:test '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)

$encodedCommand

The encoded command is now: dwByAGkAdABlAC0AaABvAHMAdAAgACQAZQBuAHYAOgB0AGUAcwB0ACAA

In your batch file, you can now have:

@echo off
set test=MyVar
Powershell -encodedcommand dwByAGkAdABlAC0AaABvAHMAdAAgACQAZQBuAHYAOgB0AGUAcwB0ACAA

When you run the batchfile, it will now print MyVar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.