2

I want to use a powershell command inside a batch file to download a file.

My code looks like that and works for just downloading the file from that specific url:

powershell "$progresspreference='silentlycontinue'; wget -uri "https://thisismyurl.com/123456" -outfile '%userprofile%\Downloads\file.zip'"

Now I want to implement echo download failed! url is invalid. & pause & goto label if the invoke-webrequest failed due to an invalid or expired url.

Also, since the powershell commands within the batch file get pretty long, is there a way to break up the commands?

I tried

powershell "$progresspreference='silentlycontinue' `
wget -uri "https://thisismyurl.com/123456" -outfile '%userprofile%\Downloads\file.zip'"

but that didn't work.

leiseg
  • 105
  • 6
  • 2
    You say that your first snippet works, but I doubt that. You would need to change ```-uri "https://thisismyurl.com/123456"``` to either ```-uri 'https://thisismyurl.com/123456'``` or ```-uri \"https://thisismyurl.com/123456\"```, for it to do so. – Compo May 06 '23 at 16:22
  • @Compo Thanks for your reply. I downloaded the file multiple times with the code I provided without any issues. What's the issue with using non-excluded double quotation marks for the url? – leiseg May 06 '23 at 16:26
  • 2
    The entire command argument from `cmd.exe` to `powershell.exe` is doublequoted, therefore without one of the modifications I've suggested, the first outer doublequote will be prematurely closed. – Compo May 06 '23 at 16:53

1 Answers1

2
  • You're calling powershell.exe, the Windows PowerShell CLI, with the implied -Command parameter, which means that the success status of the last statement in the command string determines powershell.exe's exit code: 0 in the success case, 1 otherwise.

    • In Windows PowerShell, wget is an alias for the Invoke-WebRequest cmdlet, and, as with any cmdlet, if any error occurs during its execution, its success status is considered $false and therefore translates to exit code 1.

    • Therefore, you can simply use cmd.exe's || operator to act on the case where powershell.exe's exit code is non-zero.

  • As for multiline PowerShell CLI calls from a batch file, see this answer. In short: you cannot use overall "..." enclosure and must therefore ^-escape select characters, and you must end each interior line with ^

To put it all together in the context of your code:

@echo off & setlocal

powershell $progresspreference='silentlycontinue'; ^
  wget -uri 'https://thisismyurl.com/123456' ^
       -outfile '%userprofile%\Downloads\file.zip' ^
  || (echo download failed! url is invalid. & pause & goto label)

exit /b 0

:label
  echo failure-handling branch...
exit /b 1
mklement0
  • 382,024
  • 64
  • 607
  • 775