0

Is it possible to run an entire, large, powershell script in a java application without calling it externally by launching a powershell process with the -file parameter? (passing it via the encodedcommand parameter won't work either because of the commandline lenght limitation).

I.e. is there a java library that enables you to paste your powershellscript inside your java app and run it?

I currently embed the powershellscript inside the java application and write it to disk, but I'm looking for a fileless approach.

2
  • I really don't think sending multiple commands on a single exec will work from JAVA. In that case, you have to segregate each line with newline and semicolon and may be you can give it a try with small scripts(2-3 liners) Commented Jun 1, 2017 at 15:45
  • 1
    Using powershell -Command {echo yo; $a=get-date; $a|gm; $a.date} works as expected. Keep in mind that there is a maximum command line length (1024 I think it is). You could pass additional powershell code via environment variables, which you're script could dynamically execute iex $env:pscode. Just noticed you said "large". Another approach would be to execute a small bit of PS code via command line, then pipe the bulk of the code from Java to PS. Again you'd dynamically execute the piped code. Commented Jun 1, 2017 at 23:03

1 Answer 1

1

Since you want to pass a large program, piping from the Java program to the PS script is more suitable than using the command line or environment variables. Since I don't know too much Java and don't have it installed, I'll simulate it from the PS command line in the snippet below. Your Java program would read the lines of the program from a list or some other suitable data structure (whereas this example reads it from the file system). I did see hits on google for piping from Java to an externally executed command.

cat my.ps1|
    powershell -command {$scr="";foreach ($line in $input){$scr+=$line+"`n"} echo bxb $s cxc}

After your PS stub has received the program rather than echo it, it would execute it: iex $scr.

If you need to pass parameters from Java to PS you could either pipe them along with the program (for example as lines of code that set global variables) or they could be global variables set in stub code. Other, more complex, variations are possible.

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

Comments

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.