【问题标题】:How .bat can check if curl or wget exist.bat 如何检查 curl 或 wget 是否存在
【发布时间】:2011-04-19 16:24:53
【问题描述】:

在我的 .bat 文件中,我如何通过用户可能经历的任何其他先前安装来检查系统中是否可以使用 wget 或 curl。这个检查是否可行,我的文件中是否可以有if then else 逻辑以做出不同的反应,就像我们在正常编程中所做的那样。我基本上想使用 wget 或 curl 来下载文件。

If (wget is available)
   do something
else if (curl is available)
   do something else
else 
   tell the user they are out of luck

【问题讨论】:

标签: windows curl batch-file wget


【解决方案1】:

如果您知道希望找到 EXE 的路径,那就相当容易了:

IF EXIST C:\Windows\wget.exe ( *** do something with it ***)

...当然,您可以使用 IF NOT EXIST 来复制它,或者使用 ELSE 语句。

否则,如果您不知道在哪里可以找到该文件,您可以使用以下内容搜索它(原始来源找到here):

@echo off
SETLOCAL
(set WF=)
(set TARGET=wget.exe)

:: Look for file in the current directory

  for %%a in ("" %PATHEXT:;= %) do (
     if not defined WF if exist "%TARGET%%%~a" set WF=%CD%\%TARGET%%%~a)

:: Look for file in the PATH

  for %%a in ("" %PATHEXT:;= %) do (
     if not defined WF for %%g in ("%TARGET%%%~a") do (
        if exist "%%~$PATH:g" set WF=%%~$PATH:g))

:: Results
  if defined WF (
    *** do something with it here ***
  ) else (
    echo The file: "%~1" was not found
  ) 

您可以将整个块包装成一个函数并为每个 EXE 调用一次(将 %TARGET%s 改回 %~1,给它一个 :TITLE,然后是 call :TITLE wget.exe)...

或者,您可以采取不同的方法,只尝试这些命令,看看它们是否失败。由于 ERRORLEVEL 为 0 通常意味着成功,因此您可以执行以下操作:

wget -q <TARGET_URL>
IF NOT ERRORLEVEL 0 (
  curl <TARGET_URL>
  IF NOT ERRORLEVEL 0 (
    ECHO Download failed!
    EXIT 1
  )
)
:: now continue on with your script...

【讨论】:

  • 顺便说一下,http://ss64.com/nt/ 站点是 NT CMD Shell 提示和技巧的绝佳资源。 (不要错过syntax 页面!)
  • 第二种方法对我来说已经足够好了。我认为搜索会不必要地延长脚本的执行时间。
【解决方案2】:

Powershell v3 CTP1 带有 wget/curl 之类的命令。它被称为 Invoke-Web-Request。要了解更多信息,您可以访问此帖子:http://rambletech.wordpress.com/2011/09/21/windows-powershell-v3-includes-command-like-wgetcurl/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2011-11-05
    • 2012-05-21
    相关资源
    最近更新 更多