0

I have written a basic powershell script like this:

$ "java.exe" "-cp" "." $args

My test Java program:

public static void main(String[] args)
{
    for(String arg : args) System.out.println(arg);
}

I use this script to run a Java program like this:

.\test.ps1 com.test.Test *.txt

I expect/want for this program to print this:

*.txt

Instead it prints out every file name that matches the file card in that directory like this:

1.txt
2.txt
3.txt

Does anyone have any ideas how I can prevent the wildcard expansion in the powershell script? I have tried putting double and single quotes around the &args and that doesn't work. I tried splitting all the arguments into another array and that didn't work.

Update 1:

.\test.ps1 "*.txt"

Results in the same results:

1.txt
2.txt
3.txt

Update 2:

.\test.ps1 \*.txt

Results in an incorrect argument printed:

\*.txt

Solution

I finally figured this out. You need to re-populate and quote the arguments in the powershell script like this:

$QuotedArguments = @() #Creating an array of arguments
foreach($arg in $args)
{
    #This is done because arguments with * may be expanded
    #into matching file names instead of left alone
    $QuotedArguments += """$arg"""
}
$ "java.exe" "-cp" "." $QuotedArguments
Adam
  • 121
  • 1
  • 9
  • A `test.ps1` file just contaiing `$args` outputs the arguments as is without expanding, so I'm not that shure at which the expand takes place. –  May 04 '18 at 14:18
  • Accoreding to answers in the linked Question it might be the java runtime library which does the expanding. –  May 04 '18 at 14:20
  • I looked at the "duplicate" question but it doesn't solve this problem so I don't think it is the same. E.g. test.ps1 "*.txt" results in the same behavior and test.ps1 \\*.txt results in the argument printed being: "\\*.txt". '*.txt' also results in all the txt files being printed. – Adam May 04 '18 at 14:27
  • Also, it looks like the duplicate is asking about *nix shells, not powershell. – Adam May 04 '18 at 14:35
  • The common point is java and the assumption that it's the rtl. –  May 04 '18 at 14:37

0 Answers0