Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a powershell command from run.exe

Tags:

powershell

I'm trying to run this command that works perfectly fine, but from the run.exe

(new-object System.Net.WebClient).DownloadFile("host", "filename.ext");

Tried:

powershell.exe -noexit -Command "(new-object System.Net.WebClient).DownloadFile(\"host\", \"filename.ext\");"

But I get this error:

Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:1 char:1
+ (new-object System.Net.WebClient).DownloadFile("host ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

host and filename.ext are just placeholders.

like image 663
SwagiWagi Avatar asked Nov 20 '25 12:11

SwagiWagi


1 Answers

Consider using Invoke-WebRequest instead:

powershell.exe -c "Invoke-WebRequest -Uri http://server.domain.tld/path/to/file.ext -OutFile C:\path\to\save\download\file.ext"

If you need to use the old method, which is what you attempted above, you have escaped your quotes incorrectly. The download call should look like this:

powershell.exe -noexit -Command "(new-object System.Net.WebClient).DownloadFile(`"host`", `"filename.ext`");"

Your problem with the command above is that you are trying to escape your double-quotes with a \ instead of a `. The escape character in PowerShell is `. Of course, you could always avoid the need to escape your string by using a single quote for the DownloadFile parameter instead:

powershell.exe -noexit -Command "(new-object System.Net.WebClient).DownloadFile('host', 'filename.ext');"

Note that in PowerShell, double-quoted strings can have variables and subexpressions run directly in it, and can have escaped characters. Single-quoted strings escape all special characters and thus cannot have variables or subexpressions inserted directly into them. Both single-quoted and double-quoted strings do support Format Strings, however.

like image 167
Bender the Greatest Avatar answered Nov 22 '25 04:11

Bender the Greatest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!