Capturing output from WshShell.Exec using Windows Script Host

后端 未结 5 585
无人及你
无人及你 2020-12-06 11:15

I wrote the following two functions, and call the second (\"callAndWait\") from JavaScript running inside Windows Script Host. My overall intent is to call one command line

5条回答
  •  余生分开走
    2020-12-06 11:52

    Another technique which might help in this situation is to redirect the standard error stream of the command to accompany the standard output. Do this by adding "%comspec% /c" to the front and "2>&1" to the end of the execStr string. That is, change the command you run from:

    zzz
    

    to:

    %comspec% /c zzz 2>&1 
    

    The "2>&1" is a redirect instruction which causes the StdErr output (file descriptor 2) to be written to the StdOut stream (file descriptor 1). You need to include the "%comspec% /c" part because it is the command interpreter which understands about the command line redirect. See http://technet.microsoft.com/en-us/library/ee156605.aspx
    Using "%comspec%" instead of "cmd" gives portability to a wider range of Windows versions. If your command contains quoted string arguments, it may be tricky to get them right: the specification for how cmd handles quotes after "/c" seems to be incomplete.

    With this, your script needs only to read the StdOut stream, and will receive both standard output and standard error. I used this with "net stop wuauserv", which writes to StdOut on success (if the service is running) and StdErr on failure (if the service is already stopped).

提交回复
热议问题