简体   繁体   中英

How can I use AWS-RunPowerShellScript on Windows to run a command that contains a space?

I'm trying to run a program on Windows using AWS Systems Manager (SSM) from some Java code. Here is the code:

String commands = "C:\\Program Files\\MyProgram.exe --key1=value1";
SendCommandRequest commandRequest = new SendCommandRequest()
        .withDocumentName( "AWS-RunPowerShellScript" )
        .withInstanceIds( instanceId )
        .addParametersEntry( "commands", Collections.singletonList( commands ) );

The error I get is:

C:\Program : The term 'C:\Program' is not recognized as the name of a cmdlet, 
function, script file, or operable program. Check the spelling of the name, or 
if a path was included, verify that the path is correct and try again.

I've tried putting single quotes around the command name, like this:

String commands = "'C:\\Program Files\\MyProgram.exe' --key1=value1";
SendCommandRequest commandRequest = new SendCommandRequest()
        .withDocumentName( "AWS-RunPowerShellScript" )
        .withInstanceIds( instanceId )
        .addParametersEntry( "commands", Collections.singletonList( commands ) );

But then I get this error:

+ 'C:\Program Files\MyProgram.exe' --key1=value1
+                                    ~~~~~~~~~~~
Unexpected token 'key1=value1' in expression or statement.
At C:\ProgramData\Amazon\SSM\InstanceData\i-0ad13762af97f97f1\document\orchestr
ation\784e0a71-dc7d-4a9e-944c-8820a7db6530\awsrunPowerShellScript\0.awsrunPower
ShellScript\_script.ps1:1 char:1
+ 'C:\Program Files\MyProgram.exe' --key1=value1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The '--' operator works only on variables or on properties.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx 
   ception
    + FullyQualifiedErrorId : UnexpectedToken

How can I run a command that contains spaces, and combine it with command-line arguments?

You have to escape the double quotes properly. This should work:

String commands = "\"C:\\Program Files\\MyProgram.exe --key1=value1\"";

I was not able to get Paulo's suggestion to work (I don't have the error message anymore), but I solved it by using a different approach:

String commands = "cmd /C 'C:\\Program Files\\MyProgram.exe --key1=value1'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM