0

I'm trying to run the following command but when I do it the CMD windows closes without the command being executed

the command is

cmd.exe /c powershell.exe (New-Object System.Net.WebClient).DownloadFile(https://site,'%temp%\file.txt');Start-Process '%temp%\file.txt'
1
  • 2
    Why are you opening another cmd.exe window, when you are already running your command from one? I would offer this alternative: %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -Command "(New-Object System.Net.WebClient).DownloadFile('https://domain.name/file.name', '%temp%\file.txt'); Start-Process -FilePath '%temp%\file.txt'" Commented Jan 23, 2021 at 14:35

1 Answer 1

1

You don't need cmd here at all¹. You can spawn a process without a shell just as well. Furthermore, it's usually a good idea to quote arguments to avoid surprises with argument parsing (cmd for example has its own meaning for parentheses, which may well interfere here).

powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://site',$Env:Temp + '\file.txt');Invoke-Item $Env:Temp\file.txt"

I've also added quotes around the URL you want to download, since that wouldn't otherwise work, either. And since cmd is no longer around, environment variables can be expanded by PowerShell as well, with a different syntax.

Start-Process also is for starting processes and Invoke-Item is closer to what you actually want, although I'm sure with ShellExecute behavior, Start-Process could launch Notepad with a text file as well if desired.


¹ If in doubt, it's always a good idea to reduce the number of parts, processes and different wrapped concepts needed. Same reason why you don't use Invoke-Expression in PowerShell to run other programs: Unnecessary, and complicates everything just further by introducing another layer of parsing and interpretation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.