cmd command through powershell fails with error "The string is missing the terminator: '."

70 Views Asked by At

I originally had a .bat script with the following code:

cmd /V:ON /C "set unique=nets /ao&&FOR %%A IN (0 1 2 3 2 6 2 4 5 6 0 7 1337) DO set final=!final!!unique:~%%A,1!&& IF %%A==1337 CALL !final:~-12!"

this just executes "netstat /ao". It just reconstructs each element based on an index in the loop.

To experiment further, I tried to run the following command in cmd but through powershell. The command I used was the following:

powershell -Command "Start-Process cmd.exe -ArgumentList '/c cmd /V:ON /K \"set unique=nets /ao&&FOR %A IN (0 1 2 3 2 6 2 4 5 6 0 7 1337) DO set final=!final!!unique:~%A,1!&& IF %A==1337 CALL !final:~-12!\"'"

but I get the following error:

The string is missing the terminator: '.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

I tried playing with the arguments and the way I execute the command but I always land on the same error. Any idea what Im doing wrong here?

1

There are 1 best solutions below

0
Compo On BEST ANSWER

To achieve your stated goal, i.e. run the command in cmd:

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Start-Process -FilePath \"$Env:SystemRoot\System32\cmd.exe\" -ArgumentList \"/V:On /D /K `\"@Set `\"unique=nets /ao`\" & For %G In (0 1 2 3 2 6 2 4 5 6 0 7 1337) Do @Set `\"final=!final!!unique:~%G,1!`\" & If %G Equ 1337 !final:~-12!`\"\""

For clarification:

The code is first parsed in cmd.exe, which requires that the nested -Command doublequotes are escaped. This is done using a backward slash.

This means powershell.exe sees this -Command:

Start-Process -FilePath "$Env:SystemRoot\System32\cmd.exe" -ArgumentList "/V:On /D /K `"@Set `"unique=nets /ao`" & For %G In (0 1 2 3 2 6 2 4 5 6 0 7 1337) Do @Set `"final=!final!!unique:~%G,1!`" & If %G Equ 1337 !final:~-12!`""

The remaining code for PowerShell requires that the nested doublequotes within the correctly doublequoted /K argument string are escaped. This is done using backticks, as seen above.

This means the resulting /K argument string for the -FilePath executable is:

"@Set "unique=nets /ao" & For %G In (0 1 2 3 2 6 2 4 5 6 0 7 1337) Do @Set "final=!final!!unique:~%G,1!" & If %G Equ 1337 !final:~-12!"

The actual /K string for cmd.exe in this case does not require that nested doublequtes are escaped. If you weren't sure, after reading the Command Prompt output from %SystemRoot%\System32\cmd.exe /?, you could have considered using the /S option, (along with my best practice use of the /D option).

You should note that I replaced your unnecessary && instances with & and removed your incorrect use of the Call command too. I also doublequoted your set commands, as is recommended practice.