4

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

Running command line silently with VbScript and getting output?

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

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

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

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

Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374
  • I hope that's pseudo code because you can't assign variables like that in VBScript, closest you can get is `Dim returnValue : returnValue = ...`. – user692942 Jan 22 '17 at 09:57

1 Answers1

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

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

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.

MC ND
  • 69,615
  • 8
  • 84
  • 126