2

A Unix shell (bash, dash tried) interprets a script line by line. This allows to attach some binary data to the end of the script. My particular example is a Jar file that can be automatically unzipped or run from that very script.

I wonder if this is somehow possible with PowerShell too. I tried and got errors which indicate that the PowerShell seems to parse the whole file first before starting to run it.

Is there a way to mark the rest of a file such that the PowerShell does not try to interpret it but just ignores it?

Since my specific use case is that I want to make a Jar file executable, solutions relying on base64 encoding the binary blob do not work.

To be even more explicit: the script will basically run

java -jar $MyInvocation.MyCommand.Definition @Args

such that java shall use the file as a jar file.

1 Answer 1

4

What makes you think a solution using base64 encoding wouldn't work? Convert the file to a base64 string like this:

$bytes = [IO.File]::ReadAllBytes('C:\path\to\your.jar')
[Convert]::ToBase64String($bytes)

and put the string into your script as a variable:

$jarData = 'UEsDBBQAAAAA...'

If you prefer a multiline base64 string you can wrap it like this:

[Convert]::ToBase64String($bytes) -replace '(.{80})', "`$1`n"

and put it into the script like this:

$jarData = @'
UEsDBBQAAAAA...
...
'@

Have your script decode the data and save it back to a file upon execution:

$bytes = [Convert]::FromBase64String($jarData)
[IO.File]::WriteAllBytes("$env:TEMP\your.jar", $bytes)

To my knowledge this is the only way to embed binary data in PowerShell scripts.

Sign up to request clarification or add additional context in comments.

3 Comments

The reason is the specific use case. The script will basically run java -jar \$MyInvocation.MyCommand.Definition @Args such that java shall use the file as a jar file. Consequently the jar data must be binary, not encoded.
@Harald Run java -jar "$env:TEMP\your.jar" @args instead. Problem solved.
Yeah, but this is not answering the question. It is a workaround and thanks for that. But I am in tweaking-mood. A negative answer could possibly be: "this can never work, because looking at PowerShell source (or the syntax spec or the computational model) we can see that there is no way to prevent it to parse the file to the end". Short of this I am still interested in a positive answer. BTW: it works just fine with .bat and I may settle for it despite the fact that it will fail if the script is called via a UNC path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.