1

I would like to run the following command to execute some command in a new powershell instance.

start powershell {java -jar x.jar -url $URL/computer/$name/ -secret $secret; Read-Host}

I have $URL and $name and $secret passed in as input parameters and I can echo their values without a problem.

The problem is that when the new powershell instance is started, it only sees

java -jar x.jar -url /computer// -secret

(i.e. the variable values have not been passed.) How can I solve this?

The full example script is:

param(
[parameter(Mandatory=$TRUE,Position=0)]
  [string] $URL,
[parameter(Mandatory=$TRUE,Position=1)]
  [string] $name,
[parameter(Mandatory=$TRUE,Position=2)]
  [string] $secret
)

echo $URL
echo $name
echo $secret

start powershell {java -jar x.jar -url $URL/computer/$name/ -secret $secret; Read-Host}
TToni
  • 9,145
  • 1
  • 28
  • 42
Sami
  • 7,797
  • 18
  • 45
  • 69

1 Answers1

1

By encasing your code in the brackets {} you create a code block. The Powershell interpreter will not expand anything inside the code block. Try typing { java $dummy } in the powershell command line and hit return. The return value from the (unexecuted) code block is its unexpanded content.

Normally, a code block inherits the values of external variables, so if you would execute the code block in the calling context, the variable values would be visible and could be used.

Since you start it in a new powershell process however, the variables are not set and return empty ($null) values.

So, you need to expand the variables on the way to the start command, and preserve any spaces in the expanded variables on the way to the java.exe execution. The following escaping should do the trick for you:

start powershell "java -jar x.jar -url '$URL/computer/$name/' -secret '$secret'; Read-Host"

To be on the safe side with these issues, you can use the EncodedCommand Parameter with powershell, like this:

$command = "java -jar x.jar -url '$URL/computer/$name/' -secret '$secret'; Read-Host"  # Variables get expanded here
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
start powershell "-EncodedCommand $encodedCommand"
# Or, with full parameters:
# Start-Process -FilePath powershell -ArgumentList "-EncodedCommand $encodedCommand"
TToni
  • 9,145
  • 1
  • 28
  • 42