0
votes

I'm trying to execute a PowerShell command via system() command, but encounter an exception because of the spaces in the string, I tried a few things but still got the same exception.

Code:

system("powershell.exe -command Invoke-WebRequest http://example.com/myEXE.exe -OutFile C:\\Program Files\\myEXE.exe");

And this is the exception I get:

Invoke-WebRequest : A positional parameter cannot be found that accepts
argument 'Files\myEXE.exe'.
At line:1 char:1
+ Invoke-WebRequest http://example.com/myEXE.exe -OutFile C:\Program File ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
1
Quote the OutFile: system("powershell.exe -command Invoke-WebRequest http://example.com/myEXE.exe -OutFile 'C:\\Program Files\\myEXE.exe'");Theo
That worked, Thanks! I tried doing the same thing with system("'C:\\Program Files\\myEXE.exe'"); to start the exe but it separates "Program" and "Files", any idea how to make it work?Apex
Windows can work with PROGRA~1 to address Program Files. Therefore, 'C:\\PROGRA~1\\myEXE.exe' should workTobyU
I am trying to do the same thing with %appdata% but cant make it work, and similar shortcut for it?Apex
The answer to this question points you in the right direction how you can resolve special paths (such as %appdata%) under windows. Also the proper way to run other programs (including powershell) on windows is to use CreateProcess.GSIO01

1 Answers

0
votes

I believe that this should work:

#include <iostream>
#include <bits/stdc++.h>
int main(){
    std::cout << "trying system command" << std::endl;
    system("powershell.exe -command Invoke-WebRequest https://make.sure.valid.url.to.test.otherwise.will.fail.anyways -OutFile 'C:/Program` Files/myEXE.exe'");
}

The ` charachter should allow you to properly escape the space.