如何在 Windows 中的变量中获取命令的结果? [英] How do I get the result of a command in a variable in windows?

查看:30
本文介绍了如何在 Windows 中的变量中获取命令的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将命令的结果作为 Windows 批处理脚本中的变量(请参阅 如何在 bash 中获取命令的结果 用于 bash 脚本等效项).首选适用于 .bat 文件的解决方案,但也欢迎使用其他常见的 Windows 脚本解决方案.

I'm looking to get the result of a command as a variable in a Windows batch script (see how to get the result of a command in bash for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome.

推荐答案

如果您必须捕获所有命令输出,您可以使用这样的批处理:

If you have to capture all the command output you can use a batch like this:

@ECHO OFF
IF NOT "%1"=="" GOTO ADDV
SET VAR=
FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I
SET VAR
GOTO END

:ADDV
SET VAR=%VAR%!%1

:END

所有输出行都存储在以!"分隔的 VAR 中.

All output lines are stored in VAR separated with "!".

但如果只需要单行控制台输出,请尝试:

But if only a single-line console-output is expected, try:

@ECHO off
@SET MY_VAR=
FOR /F %%I IN ('npm prefix') DO @SET "MY_VAR=%%I"

@REM Do something with MY_VAR variable...

@John:这有什么实际用途吗?我认为您应该观看 PowerShell 或任何其他能够轻松执行脚本任务的编程语言(Python、Perl、PHP、Ruby)

@John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)

这篇关于如何在 Windows 中的变量中获取命令的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆