-1

Here the Code :

@echo off
if "%*"=="" (echo Give me the URL! && exit /b)
echo Output :
set /p output=
powershell Invoke-WebRequest -Uri %* -OutFile output

The problem in this code I've written is output variable
how to send that variable into powershell ?

Mofi
  • 46,139
  • 17
  • 80
  • 143
Halano Siblee
  • 29
  • 1
  • 3
  • `if "%*"=="" (echo Give me the URL! && exit /b)` results in a syntax error if there is more than one argument string passed to the batch file enclosed in `"`. The __IF__ condition results also in an exit of the batch file processing with an error message because of a syntax error even on passing just one argument string – the url – enclosed in `"` to the batch file as it is necessary if the url contains an `&` or an `=` which urls often contain. The round brackets are completely useless here and the space left to `&&` is also output by `echo` as a trailing space. – Mofi Nov 27 '21 at 21:44
  • 1
    The unconditional operator `&` instead of the conditional operator `&&` would be enough. `echo` never fails here and so never exits with a code not equal zero. I strongly recommend to modify this command line to `if "%~1" == "" echo Run "%~nx0" with a URL!& exit /B`. The next two lines can be merged together to `set /P "OutputFile=Output file: "`. Then it is possible to reference the environment variable `OutputFile` with `'"%OutputFile:~"=%"'` whereby you would need to hope that the user really enters a file name at all and not nothing or something completely different than a valid file name. – Mofi Nov 27 '21 at 21:47
  • I recommend to read my long answer on [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) It explains on examples what can happen on using `set /P "variable=prompt text"` in a batch file without additional code to verify the user input in a safe and secure manner. – Mofi Nov 27 '21 at 21:49
  • But I do not understand why is used a batch file processed by the Windows command processor `cmd.exe` which is the most limited script interpreter available by default on Windows for an argument string verification and a very unsafe and insecure user prompt and run next its dedicated successor PowerShell being a much more powerful script interpreter. Why is the entire task not done with PowerShell? There can be done everything with a PowerShell script much better than with this combination of batch file code processed by `cmd.exe` and a PowerShell cmdlet processed by `powershell.exe`. – Mofi Nov 27 '21 at 21:52

1 Answers1

2

Use %output% to expand the output variable - and remember to quote the arguments (otherwise it'll break if someone inputs a path with spaces):

@echo off
if "%*"=="" (echo Give me the URL! && exit /b)
echo Output :
set /p output=
powershell Invoke-WebRequest -Uri '%*' -OutFile '%output%'
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206