windows - 如何在 Windows 的变量中获取命令的结果?

标签 windows scripting batch-file

<分区>

我希望将命令的结果作为 Windows 批处理脚本中的变量获取(请参阅 how to get the result of a command in bash 了解等效的 bash 脚本)。首选可在 .bat 文件中运行的解决方案,但也欢迎使用其他常见的 Windows 脚本解决方案。

最佳答案

不起眼的 for 命令多年来积累了一些有趣的功能:

D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%i
D:\> echo %today%
Sat 20/09/2008

请注意,"delims=" 会覆盖默认的空格和制表符分隔符,因此 date 命令的输出会立即被吞噬。

要捕获多行输出,它本质上仍然可以是一行(使用变量 lf 作为结果变量中的分隔符):

REM NB:in a batch file, need to use %%i not %i
setlocal EnableDelayedExpansion
SET lf=-
FOR /F "delims=" %%i IN ('dir \ /b') DO if ("!out!"=="") (set out=%%i) else (set out=!out!%lf%%%i)
ECHO %out%

要捕获管道表达式,请使用 ^|:

FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"

关于windows - 如何在 Windows 的变量中获取命令的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/108439/

相关文章:

windows - C/C++ : duplicate main() loop in many threads

batch-file - 带有服务停止/启动的通配符

ruby-on-rails - 安装 Rails gem 时,rails.bat 如何安装到 bin 目录?

c# - 如何在 C#/ASP.NET 中维护正确的 URL?

windows - 将非 unicode 库与 unicode 构建的应用程序一起使用的含义

java - Windows 上的 Java 和环境变量问题

python - 脚本语言选择

Linux Bash 脚本如何使用范围参数

javascript - "truthy"和 "falsey"的结果在 JavaScript 中很困惑

java - 为 Java 设置 Notepad++