从 VBScript 中的 cmd/c 命令获取返回值

编程入门 行业动态 更新时间:2024-10-28 00:27:23
本文介绍了从 VBScript 中的 cmd/c 命令获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在 VBScript 中,内置的 Shell.Run 方法不提供输出重定向,因此必须使用以下解决方法:

In VBScript, the built-in Shell.Run method does not provide for output redirection, so the following workaround must be used:

使用 VbScript 静默运行命令行并获取输出?

Dim retVal
retVal = WshShell.Run( "cmd /c ""commandGoesHere"" > c:\temp\output.txt", 0, True )

然而,returnValue 将具有 cmd 的返回值,而不是 commandGoesHere 的返回值.

However returnValue will have the return value of cmd, not of commandGoesHere.

我以为我可以检查 shell.Environment("ERRORLEVEL") 但大概这也是 cmd 的返回值,而不是 commandGoesHere.

I thought I could check shell.Environment("ERRORLEVEL") but presumably this would also be cmd's return value, and not commandGoesHere.

...那么我怎样才能获得 commandGoesHere 的返回值同时将其输出重定向到另一个文件?

...so how can I get commandGoesHere's return value and simultaneously redirect its output to another file?

推荐答案

returnValue = WScript.CreateObject("WScript.Shell").Run( _ 
    "cmd /v /c (>""output.txt"" ""commandGoesHere"" & exit !errorlevel!)" _ 
    , 0 _ 
    , True _ 
)

启动 cmd 实例并启用延迟扩展 (/v) 并退出 cmd 实例并带有 errorlevel 由上一个命令设置.

Start the cmd instance with delayed expansion enabled (/v) and exit the cmd instance with the errorlevel set by the previous command.

需要延迟扩展,因为 cmd 解析器在行/块解析阶段用变量内部的值替换所有 %var% 读取操作.在没有延迟扩展(%errorlevel%)的情况下,exit 命令返回的值将在开始执行命令之前被检索.使用延迟扩展 (!errorlevel!),在 commandGoesHere 结束后,执行 exit 命令时将检索该值.

Delayed expansion is needed because the cmd parser replaces all %var% read operations with the value inside the variables during the line/block parse phase. Without delayed expansion (%errorlevel%), the value to be returned by the exit command will be retrived before starting to execute the command. With delayed expansion (!errorlevel!) the value will be retrieved when the exit command is executed, after the commandGoesHere has ended.

这篇关于从 VBScript 中的 cmd/c 命令获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 00:05:15,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   命令   VBScript   cmd

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!