windows - 批处理文件 - 检查命令是否可用

标签 windows batch-file cmd

我正在 Windows 中编写一个需要运行 nodejs 应用程序的小批处理文件。在运行该应用程序之前,我需要确保该节点已由用户安装,如果没有,则向他显示一条消息,表明该节点是必需的。

我做的是这样的:

@echo OFF

setlocal EnableDelayedExpansion

REM Check if node is installed
for /f "delims=" %%i in ('node -v') do set output=%%i

IF "!output!" EQU "" (
    echo node could not be found
) else (
    node %~dp0app.js
)

如果用户安装了节点,那么 output 将包含版本号。如果没有安装,那么它将是空的。这个逻辑有效。但是如果没有安装node(node -v command not found),批处理结果也会显示如下输出:

'node' is not recognized as an internal or external command,
operable program or batch file.
node could not be found

我想对用户隐藏“无法识别”消息,只显示“找不到节点”。

如何隐藏它?

最佳答案

要抑制错误消息,将其重定向到 NUL:

set "output=not installed"
for /f "delims=" %%i in ('node -v 2^>nul') do set output=%%i
echo %output%

另一种方式(受 Npocmaka 的回答启发):

where node.exe >nul 2>&1 && echo installed || echo not installed

或者为了更接近您的原始输出:

where node.exe >nul 2>&1 && node %~dp0app.js || echo node could not be found

关于windows - 批处理文件 - 检查命令是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34930335/

相关文章:

c++ - 将特定的逻辑核心专门分配给特定的进程,Windows,C++

python - 如何在 python 中连接/断开连接/配置无线网络?

c# - System32 是否仍需要安装屏幕保护程序?

batch-file - 批处理文件,使用 dir 命令进行字符串操作

c++ - 提高 Windows 应用程序的性能

angularjs - 如何在没有 Node 的情况下本地运行 Angular 2 应用程序

windows - 如何使用批处理文件重命名或创建包含其内容名称的 zip 文件

c# - 将 XML 字符串作为参数传递给 Process.Start

vba - 如何在 Windows 上自动切换飞行模式

java - 如何隐藏java进程的参数?