0

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Apex
  • 61
  • 9
  • 2
    Quote the `OutFile`: `system("powershell.exe -command Invoke-WebRequest http://example.com/myEXE.exe -OutFile 'C:\\Program Files\\myEXE.exe'");` – Theo Dec 05 '18 at 14:23
  • 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 Dec 05 '18 at 14:33
  • Windows can work with `PROGRA~1` to address `Program Files`. Therefore, `'C:\\PROGRA~1\\myEXE.exe'` should work – TobyU Dec 05 '18 at 14:54
  • I am trying to do the same thing with %appdata% but cant make it work, and similar shortcut for it? – Apex Dec 05 '18 at 15:10
  • The answer to [this question](https://stackoverflow.com/questions/3964124/how-to-get-the-appdata-folder-in-c) 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](https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa). – GSIO01 Dec 05 '18 at 15:16
  • I know this function and have used it before, but the return value of it makes it hard for me to combine with a system() string, and that's why I'm trying to use %appdata% directly :/ – Apex Dec 05 '18 at 15:43

1 Answers1

0

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.

9301293
  • 514
  • 3
  • 16
  • The powershell command already works with the solution suggested above, I tried your solution with my second command that doesn't work but it didn't even let me include the ... This is the command I need working: system("'C:\\Program Files\\myEXE.exe'"); – Apex Dec 06 '18 at 09:39