Search code examples
powershellbatch-filecmdinvoke-webrequest

How to echo if invoke-webrequest failed due to an invalid/expired url else continue download in Powershell CLI?


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.


Solution

    • 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