China DOS Union

-- Unite DOS · Advance DOS · Grow DOS --

Union site: www.cn-dos.net Forum site: www.cn-dos.net/forum
DOS stands for freedom, openness and progress. Let us work hard, learn from the openness and GNU spirit of FreeDOS and Linux, and together build and grow a free GNU GPL world!

中国DOS联盟论坛
The time now is 2026-07-15 00:19
中国DOS联盟论坛 » DOS批处理 & 脚本技术(批处理室) » [vbs] Script to intercept cmd command output (注:原内容中“vbs”是“Visual Basic Script”的缩写,按要求保留格式翻译为“[vbs] Script to intercept cmd command output”) View 6,358 Replies 13
Original Poster Posted 2006-06-07 17:13 ·  IANA 局域网IP(Private-Use)
铂金会员
★★★★
Credits 7,493
Posts 2,672
Joined 2005-09-02 00:00
20-year member
UID 42173
Gender Male
Status Offline
It took a long time to discover that WScript.Shell has such a great function!


Set objShell = CreateObject("WScript.Shell")
Set objExecObject = objShell.Exec ("%comspec% /c " & wscript.arguments(0))
Do While Not objExecObject.StdOut.AtEndOfStream
strText = objExecObject.StdOut.ReadAll()
loop
msgbox strText


Save it as GetStdOut.vbs, and in the command line, navigate to the corresponding directory and run:
cscript.exe GetStdOut.vbs "ping 127.1"

Look, isn't this coming out:



Pinging 127.0.0.1 with 32 bytes of data:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms



[ Last edited by electronixtar on 2006-6-7 at 17:19 ]
Recent Ratings for This Post ( 3 in total) Click for details
RaterScoreTime
redtek +3 2006-11-24 14:07
lxmxn +2 2006-12-29 00:35
jmz573515 +4 2006-12-29 04:10
Floor 2 Posted 2006-06-07 17:41 ·  中国 北京 联通
银牌会员
★★★
DOS联盟捡破烂的
Credits 1,144
Posts 425
Joined 2005-10-20 00:00
20-year member
UID 43784
From 北京
Status Offline
In fact, for VBS scripts, the operation of pipes is still necessary to a certain extent. And there are certain differences between the properties and methods of WSCRIPT.SHELL and the pipe commands executed by EXEC, but they are generally the same
Floor 3 Posted 2006-06-08 21:47 ·  中国 四川 成都 联通
铂金会员
★★★★
Credits 7,493
Posts 2,672
Joined 2005-09-02 00:00
20-year member
UID 42173
Gender Male
Status Offline
BagPipe has changed the avatar and signature. Hehe~

C:\>BLOG http://initiative.yo2.cn/
C:\>hh.exe ntcmds.chm::/ntcmds.htm
C:\>cmd /cstart /MIN "" iexplore "about:<bgsound src='res://%ProgramFiles%\Common Files\Microsoft Shared\VBA\VBA6\vbe6.dll/10/5432'>"
Floor 4 Posted 2006-06-09 03:23 ·  中国 山西 运城 中移铁通
元老会员
★★★★
Batchinger
Credits 4,432
Posts 1,512
Joined 2002-10-18 00:00
23-year member
UID 19
Gender Male
Status Offline
Re electronixtar:

For this topic, the following linked article explains it in detail.

Quoted from: Microsoft TechNet: Script Talk -- October 2002: Running Programs from WSH Scripts
http://www.microsoft.com/china/technet/archives/columns/scripts/sg1002.asp


Script Talk -- October 2002
Running Programs from WSH Scripts
Scripting Expert Group



The Scripting Expert Group sincerely welcomes you to visit this newly opened monthly column. We originally hoped to create this column on our own, but we really couldn't manage it. As you can see, this is not really our column; it belongs to you. You send a large number of carefully prepared emails to scripter@microsoft.com, and this column is precisely (and will continue to be) based on the questions and comments you provide. For this reason, the Scripting Expert Group can welcome everyone to visit their own column in an orderly manner; we sincerely hope you can find information here that is both pleasing to the eye and of practical value. If the content presented in this column does not satisfy you, please feel free to give us your advice!

One of the more common questions we receive is how to run a program from a WSH script. The following is a representative excerpt from such an email.

You mentioned in the webcast two lines of script code that help you run an external program. Can you provide an example sample of the code?

In response to the above question, we have decided to take up the first issue of this column to introduce you to how to run external programs from your own scripts. Why do you need to run an external program from a script? Just imagine: command-line tools allow you to perform a set of specific tasks, and batch scripts provide the necessary logical threads for you to stitch these tasks together to build the basic elements of a custom solution. But what if the logical threads provided by the batch script are not powerful enough, or the necessary components to build the solution are not provided by the command-line tool? This is where WSH scripts come into play. Such scripts allow you to apply the powerful logical threads provided by scripting languages such as VBScript, and use powerful tools such as WMI and ADSI as well as command-line tools and batch scripts to implement your own task solutions.

Let's immediately start writing an example script. In fact, we should first make sure there is a physical location to save this script before writing the script. If there is no folder named C:\Scripts on the computer you are using, please go back to the root directory and create this folder. When you have completed the above work, you should open Notepad or other text editor, type the following script code, and save it to your C:\Scripts folder with the file name RunIPConfig.vbs.

Set objShell = CreateObject("Wscript.Shell")
objShell.Run "ipconfig"

Before trying to run the script you just generated, let's check it and try to predict the possible running result in advance. There are two hints in this script that help us predict the running result. The first line of code includes the verb Create (actually CreateObject), and the second line of code contains the verb Run (run). It can be seen that this script may first generate something called an object and then run a specific program. In fact, it looks more like the script will run a command-line tool named ipconfig.exe.

The above prediction does match the running result of the script. The script first generates something called an object. In this example, the object generated by the script is the Shell (WshShell) object. You can think of an object as something similar to a command-line tool; and your script can use it to perform a specific type of task. The Shell object allows you to perform tasks that could originally be performed in the Windows command interpreter from the script--like running a program.

Unlike a command-line tool, you must first generate a new object before starting to apply it. When generating the object, you should also assign it a name that will be used to reference it in the rest of the script. In this example, the name we use is objShell. When the object is generated and given a relevant name, we can use the object to perform relevant tasks by adding a dot (.) after the object name and then the name of the task to be completed. The task name in this example is Run. And Run is a well-known Shell object method.

Now, open a command-line window and navigate to the C:\Scripts folder. To run the script you just wrote, please enter the cscript RunIPConfig.vbs command and press Enter. You will see a window flash on the screen, but the content displayed in the window disappears before you can see it! You can try running the script repeatedly and try to decipher the information that disappears in the window. This may be an interesting thing, but it can be done in a simpler way.

To make it easier for you to understand, we must pay attention to the events that occur while you are running the command-line tool. When you enter ipconfig at the command line and press Enter, you issue an instruction to the command interpreter. The command interpreter will check the instruction you entered. If the command you entered represents a valid program, the command interpreter will run the program for you. If the command you entered does not represent a valid program, the command interpreter will inform you of the relevant situation by displaying an error message. The command interpreter based on the Windows NT operating system is Cmd.exe. And the command interpreter in the Windows 9x operating system is Command.exe.

At this moment, the objShell.Run "ipconfig" command in the above script will run the ipconfig program while bypassing the command interpreter; in other words, the command will run ipconfig directly without first running the command interpreter and then having the command interpreter run ipconfig. In some cases, this method may have more advantages than disadvantages, but in this example, we do not want to bypass the command interpreter. Why? Because the command interpreter can help us find the answer to the "window flashes by" problem. As you can see, the command interpreter can accept a large number of switch options (if you are interested in all the functions of cmd.exe or command.exe, please look up the executable file of this program in the computer help system), and the /k switch in these options is exactly used to instruct the command interpreter to keep the output window open after a program runs. We need to use this option to ensure that the program window does not close immediately after opening.

To achieve the above purpose, we should modify the command being run from ipconfig to cmd.exe /k ipconfig or command.exe /k ipconfig, where cmd.exe corresponds to the Windows NT operating system and command.exe is suitable for the Windows 9x operating system. But what if you have to support both Windows NT and Windows 9x operating systems? It is quite troublesome to track the operating system we are using. It is for this reason that we quoted an environment variable named %COMSPEC% to provide the complete path to the appropriate command interpreter. This environment variable ensures that the following script code can run on both the Windows NT operating system and the Windows 9x operating system:

Set objShell = CreateObject("WScript.Shell")
objShell.Run "%COMSPEC% /k ipconfig"

Please try to run this modified script. You just need to start Notepad (or other file editor you are used to), add %COMSPEC% /k to the previously written script, and then save the modified file as RunIPConfig.vbs. Next, navigate to the C:\Scripts directory in the command-line window, and then run the script by entering the cscript RunIPConfig.vbs command and pressing Enter. This time you will see a new window displaying the output of the ipconfig command, as shown in the following figure.


If your browser does not support the embedded frame, please, click here to browse in a separate page.

What you should do next is to test for applicability. The program that the above script can run is not limited to ipconfig. All you need to do is modify the string after the Run method in the second line. You can try replacing %COMSPEC% /k ipconfig with %COMSPEC% /k netstat or %COMSPEC% /k mmc respectively. For example, you can run a GUI (graphical user interface) tool from a script, and this script takes running the calculator program as an example:

Set objShell = CreateObject("WScript.Shell")
objShell.Run "Calc.exe"

You can not only run other scripts from within a script, but also call other batch files from the current script; if you happen to have some batch files, you can try running them. Of course, if the storage location of these batch files does not match the setting range of the PATH environment variable on your computer, you should add the relevant storage location to the global access path or specify the complete access path to the batch script separately. For example, if you have a batch script named Checkserver.bat in the C:\Batchscripts directory, then the string you pass to the Run method should be similar to: %COMSPEC% /k C:\batchscripts\checkserver.bat.

If you have completed the above experiment, we will continue to explain the following content. You will learn how to use the Run method to run a single program. What should you do if you need to run two programs consecutively? This is exactly the task that the following script will perform: the script will run the ping program and then the nslookup program immediately. Please note that you can include the command-line parameters corresponding to the program you need to run in the string passed to the Run method. Here, we will pass 127.0.0.1 as parameters to Ping and Nslookup respectively.

Set objShell = CreateObject("WScript.Shell")
objShell.Run "%COMSPEC% /k ping 127.0.0.1"
objShell.Run "%COMSPEC% /k nslookup 127.0.0.1"

Please save and run this script according to the processing method for the previously described script. The running result of the script should be that two command-line windows open at the same time, where the Nslookup program runs in one window and the Ping program runs synchronously in the other window, as shown in the following screenshot.


If your browser does not support the embedded frame, please, click here to browse in a separate page.

In this example, it turns out that it is not a problem at all to run Ping and Nslookup at the same time. However, what if you need to run two batch scripts and want the second script to start running only after the first script has finished running? For example, the first program will retrieve a certain type of information and save it as a text file; the second program will then read the just-generated text file and perform specific operations on the relevant content. In this case, running the two programs at the same time is not acceptable; the second program can only start running if the first program has finished executing.

So far, we have been passing a string to the Run method to specify the program we need to run. The Run method can accept two more parameters, each of which is optional. The second parameter will allow you to specify the appearance of the window when a program starts running. Not all programs will use this parameter, but for those that do, this parameter can help you start a program that presents a variety of window styles, including minimized, maximized, and hidden. We are not going to go into too much detail about this parameter in this column article. If you need to know more information about this parameter, please refer to the WSH online documentation http://msdn.microsoft.com/library/default.asp?url=/nhp/Default.asp?contentid=28001169 (click the "Windows Script Host Documentation" link near the top of this page).

The third parameter specifically for the Run method will allow us to prevent related programs from running concurrently. You can assign the third parameter a value of True to instruct the script to stay on the line of code using the Run method and wait until the activated program has finished running. We already know the consequences of not setting this parameter. The parameter is set to False by default, and this setting will definitely cause two programs to run at the same time.

Let's modify the previous script to the state where the Ping program runs first and then the Nslookup program runs after the Ping program has finished running.

Set objShell = CreateObject("WScript.Shell")
objShell.Run "%COMSPEC% /k ping 127.0.0.1",,True
objShell.Run "%COMSPEC% /k nslookup 127.0.0.1"

Please note that we have added the third parameter assigned as True to the Run method called in the second line of the script. The reason we use two commas in a row is that if we use only one comma, then the Run method will think that what we specify next is the second parameter, not the third parameter. As you can see, there is nothing between the two consecutive commas, so no setting will be passed to the Run method as the second parameter. If we do not assign a specific value to a parameter, the Run method will use the default value. For example, the default value of the third parameter should be False.

Now let's try to run the modified script. You will immediately notice that only the Ping program is run. When Ping finishes running, the window used by the program remains open on the screen; the Nslookup program has not started running yet. Try to close this window and see what happens next. When you close the window used by the Ping program, Nslookup will start running. Please remember that you are running cmd.exe (or command.exe) with the /k option, which means you have told the Run method to continue executing subsequent instructions only when cmd.exe has finished running. Well, since we set the /k option in advance, cmd.exe will only finish executing when the window that was required to stay open is closed.

If you need to run two batch files and do not need to view their output, you can delete the /k option, and the two batch files will still run consecutively (instead of simultaneously), which is exactly the running method you need to ensure when the second program depends on the running result of the first program.

There should be communication between the two programs, that is, the fact that the first program has been run must be informed to the second program. Some programs will return an error code (that is, a number) to indicate whether they have been successfully run. And the Run method can return this error code to the script you wrote. The program that is running must finish running before the error code to be returned is known, so you must force the script to wait for the program to finish running by setting the third parameter of the Run method to True.

We will run the Ping program in the next script and display the error code returned by this program by using the Echo command for the Wscript object. The Wscript object does not need to be generated in the same way as the WshShell object, and you can use the methods it provides at any control point in the script.

Set objShell = CreateObject("Wscript.Shell")
iErrorCode = objShell.Run("ping 127.0.0.1",,True)
Wscript.Echo iErrorCode

In addition to having the error code retrieval function, the above script is different from the previous script in two aspects. First, please note that the string to be passed to the Run method has been enclosed in a pair of parentheses. This is mainly because Run is currently required to return a value. This is a requirement of the VBScript language; if you do not use parentheses here, you will receive an error message during script execution. The value that should be returned is the error code of the Ping program, and it will be saved in the variable iErrorCode, and then displayed with the WScript.Echo command.

The second thing to pay attention to is that we are not running the command interpreter. We want the error code to come from Ping, not from Cmd.exe (or Command.exe), so we directly run the Ping program. The error code returned by Ping is neither very interesting nor very useful. Of course, some command-line tools can return useful error codes that can be used by the script you write to make judgments (or generate logs).

The relevant information obtained from a program run by Run has only the minimum usage requirements and is likely not very useful. For example, many programs will only return a 0 value to indicate that they have been run and have finished running. Of course, they don't have to report to you that they have run and finished successfully.

Of course, if you have WSH version 5.6 (available for download from the http://msdn.microsoft.com/library/default.asp?url=/nhp/Default.asp?contentid=28001169 page), you have another method available to run programs that can help you improve the information exchange method with the currently running program. And this method is Exec. It is also a method belonging to the WshShell object, and the WshShell is the object that must be generated to use Run. This mainly means for us that we don't need to modify the first line of code of the script to start using the Exec method.

Let's directly write a script that uses the Exec method to run the ipconfig program.

Set objShell = CreateObject("WScript.Shell")
objShell.Exec "%COMSPEC% /k ipconfig"

The only difference between the above script and the second script we showed you is that we have changed objShell.Run to objShell.Exec in this script. However, when you run this script, you will hardly notice the effect of this modification. You can't even see the window that flashes by. In fact, you can't see anything. If we tell you now that ipconfig has actually finished running, would you be willing to believe it? Well, don't believe us easily; instead, add a redirection symbol (>) after the ipconfig command and follow a text file name after the call to ipconfig. The above code will cause the command execution result to be output to the specified file. If you are not used to using redirection operations, you can think of it this way: if we tell you the truth, and the ipconfig program is indeed running, then it will generate its own standard text display information. Unfortunately, we won't be able to see the relevant information. Redirection operations will allow us to capture the output of any command and force them to be directed to a specified file. This will help us confirm whether the ipconfig command is running. The following script can be used to present the output results we need to view to us.

Set objShell = CreateObject("Wscript.Shell")
objShell.Exec "%COMSPEC% /k ipconfig > ipconfig_output.txt"

After the above script runs, please check the content of the ipconfig_output.txt file. To view the content of this text file, please type the type command as shown in the following screenshot.


If your browser does not support the embedded frame, please, click here to browse in a separate page.

This is the information you get! Our script is actually running ipconfig, but we didn't see the command output result. Whether you believe it or not, this is a good thing. The reason why Exec does not display the output result for us is precisely because we did not originally make such a request. As you can see, we can use Exec to control the presentation and operation methods of the output result.

Do you still remember how to make the Run method return an error code? Exec can actually return a complete object called WshScriptExec. Just as the WshShell object provides us with access to the Run and Exec methods, the WshScriptExec object provides us with access to additional functional features, and these additional functional features allow us to operate around the output result of a program. The implementation of a large number of operations in the script will come at the cost of additional complexity, and the above additional functional features are no exception. We are going to encounter this complexity more or less, so please continue reading this article and make sure to concentrate in the next section.

The Exec method can be used to return a WshScriptExec object. And to make this happen in a script, the Set keyword in the VBScript language needs to be used, as shown in the following code:

Set objWshShellExec = objShell.Exec("ipconfig")

Explanation: We are not continuing to use the %COMSPEC% environment variable here; this variable is no longer necessary, mainly because we don't need to pass the /k option to the relevant command to ensure that a non-existent window is kept open. Then, how can we close this window and continue running the script code? We can use the /c option here (this option means to run only one command and then continue executing the subsequent code); in fact, if we need to run a command built into the command interpreter (such as dir), we will need to use this option. Tools like dir themselves are not in the tool category; they are more like parameters of the cmd.exe (or command.exe) command; for this reason, you need to specify the %COMSPEC% environment variable to ensure that they work.

When you store the reference related to the WshShellExec object in the objWshShellExec variable, you have the necessary conditions to start operating around the program output result, but the conditions are not yet sufficient. This is where complexity steps in. Just as the Exec method returns the WshScriptExec object, the WshScriptExec object can also return another object; this object will be returned by calling the StdOut property, and this just allows you to perform related operations on the program output result.

This idea is almost impossible to understand without referring to an example script. Therefore, we have specially written the simplest example to apply the output result generated by a program nested in a WSH script. Please treat this script as a special type of redirection operation. In this case, the program output result will not be imported into a file; instead, the relevant output result will be assigned to a variable named strOutput. Unfortunately, this time we can't just use a simple redirection symbol (>), but we must operate around two different objects.

Set objShell = CreateObject("WScript.Shell")
Set objWshScriptExec = objShell.Exec("ipconfig")
Set objStdOut = objWshScriptExec.StdOut
strOutput = objStdOut.ReadAll
WScript.Echo strOutput

The output result generated by the above script will be displayed in the window dedicated to running the script; no new window is generated. In fact, if you run ipconfig itself from the command line, the output result will look the same. If that's the case, why not just take this approach? We have generated an intermediate storage location for the output result in the script--the strOutput variable. Although we will use the Wscript.Echo command to display the output result in the next line of the above script, we often need to manipulate the output result before performing the display operation, so that we can modify the information displayed by the ipconfig tool.

Before trying to run the above script, let's pay more attention to its last three lines of code; of course, you are already very familiar with the first two lines of code. In the third line of code, the StdOut property equipped with the WshScriptExec object will be used to retrieve the relevant object representing the (standard) output result of the program that is running; and ipconfig is the output program of the result to be processed in this example. In the fourth line of code, the ReadAll method will be used to retrieve all the output results and save them in the strOutput variable. Finally, in the fifth line of code, WScript.Echo will be used to display the output result.

We now have an object that is often used as a wrapper program for the ipconfig tool (or any other tool we can use to replace ipconfig in the above script). A wrapper program is a special program that can apply the functional characteristics of another program and can modify the function of the encapsulated program in a simple and fast way. The wrapper program creates an ideal opportunity for us to modify the output result of the encapsulated program. And this is exactly what we will introduce in the remaining part of this article.

In customizing around the ipconfig tool, we will need to understand how to process the program output result line by line. Currently, we mainly use objStdOut.ReadAll to retrieve all the output results of the ipconfig tool and save the retrieved results in the strOutput variable. The task we will perform in the next script is to use ReadLine (instead of ReadAll) to retrieve the output result line by line. We will check each line of the output result, and if any line includes the string "Physical Address" (physical address), we will display it; otherwise, we will not display this line of output result. We only filtered the output result line containing the string "Physical Address" (physical address, which is the MAC address corresponding to the network card), and did not display anything else.

Set objShell = CreateObject("WScript.Shell")
Set objWshScriptExec = objShell.Exec("ipconfig /all")
Set objStdOut = objWshScriptExec.StdOut

While Not objStdOut.AtEndOfStream
strLine = objStdOut.ReadLine
If InStr(strLine, "Physical Address") Then
WScript.Echo strLine
End If
Wend

The first three lines of the above script look a bit familiar; please note that we must add the /all option to the ipconfig command to ensure that Physical Address (physical address) is displayed. The main difference between this script and the previous script is that the former uses the While/Wend loop statement. We will use the ReadLine method to retrieve a single output result line, but we need to master the specific means to determine whether we have exceeded the line retrieval range. This is where the While/Wend loop and the objStdOut.AtEndOfStream instruction come into play. As long as the program has not reached the end of the (standard) output result data stream, the above loop will continue to execute (and the output result line that meets the retrieval conditions will be saved in the strLine variable). You can think of a data stream as a long string composed of a series of characters, and you can process it in the order of arrangement; the data stream in this example is the complete output result of the ipconfig /all command.

Whenever we complete a program loop, we will save the next line of content in the strLine variable and use the If/Then statement to decide whether to display this line of content. We mainly use the InStr (string command) function to determine whether the output result line stored in the strLine variable contains "Physical Address" (physical address). If the current line does contain "Physical Address" (physical address), it should be displayed using the WScript.Echo command. The following screenshot shows part of the typical output result generated by the script.


If your browser does not support the embedded frame, please, click here to browse in a separate page.

Our next script will use the same basic components as the previous script, except that we no longer filter the output result, but add specific content to them. Since the ipconfig /all command can retrieve information about DHCP release acquisition time and its timeout status, it may be useful to include the current date and time in the processing of the command output result. The following script is exactly to realize this idea.

The script starts by retrieving and displaying the first four lines of the output result, and the method used for each line is exactly the same--first call the ReadLine command, and then call the WScript.Echo command. When the fourth line of the output result has been retrieved and displayed, we generate a string containing the current date and time annotation information. The current date and time here are provided by the Now() function equipped with VBScript.

Set objShell = CreateObject("WScript.Shell")
Set objWshScriptExec = objShell.Exec("ipconfig /all")
Set objStdOut = objWshScriptExec.StdOut

'
' Skip first four lines
'
strLine = objStdOut.ReadLine
WScript.Echo strLine
strLine = objStdOut.ReadLine
WScript.Echo strLine
strLine = objStdOut.ReadLine
WScript.Echo strLine
strLine = objStdOut.ReadLine
WScript.Echo strLine

'
' Add date/time information
'

strCurrentTime = " Current Date/Time. . . . . . . . .: " & Now()
WScript.Echo strCurrentTime

'
' Display the rest of the output
'

While Not objStdOut.AtEndOfStream
strLine = objStdOut.ReadLine
WScript.Echo strLine
Wend

There is no doubt that the above script has started to become a bit more complicated. And the best way to interpret this script is to analyze it section by section. You should be familiar with the first three lines of the script. The next commented part mainly uses the ReadLine and Echo commands to read and display the first four lines of the ipconfig /all output result.

The next commented part naturally starts with arranging the new information line that will be temporarily stored in the strCurrentTime variable. This information line will be composed of a simple string associated with the VBScript Now() function call operation, and the VBScript Now() function is used to provide current date and time information. Once this information line is arranged and saved in the strCurrentTime variable, we can immediately use the WScript.Echo command to display it.

In the last commented part, we will loop through the remaining content of the output result and display it line by line without any modification. The following screenshot shows the typical output result generated by the script. Please note that the script output result looks the same as the standard output result of ipconfig. And the Current Date/Time (current date/time) line inserted by us below the Host Name (host name) line fits seamlessly with the new context.


If your browser does not support the embedded frame, please, click here to browse in a separate page.

Finally, let's use the For/Next loop statement to perform the output operation of the first four lines to make the script more concise, as shown in the following code.

Set objShell = CreateObject("WScript.Shell")
Set objWshScriptExec = objShell.Exec("ipconfig /all")
Set objStdOut = objWshScriptExec.StdOut

'
' Skip first four lines
'
For i = 1 To 4
strLine = objStdOut.ReadLine
WScript.Echo strLine
Next

'
' Add date/time information
'

strCurrentTime = " Current Date/Time. . . . . . . . .: " & Now()
WScript.Echo strCurrentTime

'
' Display the rest of the output
'

While Not objStdOut.AtEndOfStream
strLine = objStdOut.ReadLine
WScript.Echo strLine
Wend

In fact, there is another alternative method to run other programs from the WSH script: to apply Windows Management Instrumentation (WMI). You can use WMI to complete a series of Windows management tasks! Although the way to run a program using WMI will involve relatively complex syntax, it can help you complete tasks that Run and Exec cannot achieve, such as setting the program running priority or running related programs based on a remote computer. Here, we sincerely suggest that you try to learn more about WMI. If you are really interested in this (we hope you will be), please go to a column called Scripting Clinic (Script Clinic) on the MSDN website to check the three-part series of articles (http://msdn.microsoft.com/columns).

Fortunately, we have answered some of your questions about running other programs from the WSH script. We also provided a brief overview of the Run and Exec methods and initially touched on some of the differences between them--the most obvious difference is that the Exec method allows you to process the program output result, while the Run method does not have this ability. Another important difference is that the Exec method is only available in WSH 5.6 and later versions.

We sincerely hope you are satisfied with the first column article. Please send your opinions and views to: scripter@microsoft to let us know. In addition, be sure to tell us what content you want the columns in the future to cover. If you can spare some valuable time, please refer to the WMI series of articles published in the Scripting Clinic (Script Clinic) column; if you use the knowledge and skills learned here to complete some work that is both concise and practical, please record the process; we are very happy to hear about such news!
Recent Ratings for This Post ( 3 in total) Click for details
RaterScoreTime
redtek +3 2006-11-24 14:08
jmz573515 +4 2006-12-29 04:11
kioskboy +2 2008-04-15 12:40
※ Batchinger 致 Bat Fans:请访问 批处理编程的异类 ,欢迎交流与共享批处理编程心得!
Floor 5 Posted 2006-06-09 10:55 ·  中国 四川 成都 联通
铂金会员
★★★★
Credits 7,493
Posts 2,672
Joined 2005-09-02 00:00
20-year member
UID 42173
Gender Male
Status Offline
Hehe, right!

Recently researching XMLHttp, for website automatic login, I need to output a .js with a function. I use WshShell.Exec "cscript xxxx.js //NoLogo" to get the function value. Hehe~ A very useful method~

C:\>BLOG http://initiative.yo2.cn/
C:\>hh.exe ntcmds.chm::/ntcmds.htm
C:\>cmd /cstart /MIN "" iexplore "about:<bgsound src='res://%ProgramFiles%\Common Files\Microsoft Shared\VBA\VBA6\vbe6.dll/10/5432'>"
Floor 6 Posted 2006-06-11 17:51 ·  中国 河南 郑州 电信
初级用户
★★
Credits 136
Posts 59
Joined 2006-06-02 16:05
20-year member
UID 56438
Status Offline
Floor 7 Posted 2006-09-19 08:29 ·  新加坡 腾讯云
初级用户
Credits 73
Posts 30
Joined 2006-09-18 08:35
19-year member
UID 62944
Status Offline
'''SYSTEMINFO is not convenient to output text files under CMD, just use standard output!
'''Usage of self - contained parameters ---------By MOBO[墨伯]:

Set objShell = CreateObject("WScript.Shell")
Set objExecObject = objShell.Exec("%comspec% /c SYSTEMINFO /FO LIST" )

'''Read the standard output after running:
Do While Not objExecObject.StdOut.AtEndOfStream
strText = objExecObject.StdOut.ReadAll()
Loop

'''Output with text file:
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.CreateTextFile("SYSTEMINFO.txt", true)
ts.Write strText
Set ts=nothing
Set fso=nothing
'''Originally wanted to output with web page, but it is not beautiful!
Floor 8 Posted 2006-09-19 08:58 ·  中国 四川 成都 教育网
铂金会员
★★★★
Credits 7,493
Posts 2,672
Joined 2005-09-02 00:00
20-year member
UID 42173
Gender Male
Status Offline
If there are VBS + WMI, there's no need to bother with systeminfo.

C:\>BLOG http://initiative.yo2.cn/
C:\>hh.exe ntcmds.chm::/ntcmds.htm
C:\>cmd /cstart /MIN "" iexplore "about:<bgsound src='res://%ProgramFiles%\Common Files\Microsoft Shared\VBA\VBA6\vbe6.dll/10/5432'>"
Floor 9 Posted 2006-10-08 21:14 ·  中国 湖北 武汉 电信
版主
★★★★★
Credits 11,386
Posts 4,938
Joined 2006-07-23 17:10
19-year member
UID 59080
Status Offline

I did as the thread starter said, but the result didn't show up.

Just a msgbox popped up, with no messages in it. What's going on here?
Floor 10 Posted 2006-10-08 21:46 ·  中国 四川 成都 教育网
铂金会员
★★★★
Credits 7,493
Posts 2,672
Joined 2005-09-02 00:00
20-year member
UID 42173
Gender Male
Status Offline
Won't it be? Pay attention to having parameters

C:\>BLOG http://initiative.yo2.cn/
C:\>hh.exe ntcmds.chm::/ntcmds.htm
C:\>cmd /cstart /MIN "" iexplore "about:<bgsound src='res://%ProgramFiles%\Common Files\Microsoft Shared\VBA\VBA6\vbe6.dll/10/5432'>"
Floor 11 Posted 2006-10-08 22:21 ·  中国 湖北 武汉 电信
版主
★★★★★
Credits 11,386
Posts 4,938
Joined 2006-07-23 17:10
19-year member
UID 59080
Status Offline
Originally posted by mobo at 2006-9-19 08:29:
'''SYSTEMINFO in CMD is not convenient to output to a text file, just use standard output


You can output to a text file. Why do you say it's inconvenient?
Floor 12 Posted 2006-12-28 12:11 ·  中国 湖北 武汉 电信
版主
★★★★★
Credits 11,386
Posts 4,938
Joined 2006-07-23 17:10
19-year member
UID 59080
Status Offline

  Tried again, and it果然 works. It seems I made a mistake earlier by not adding parameters.

  Also, the effect of the mobo's vbs script is the same as systeminfo > systeminfo.txt. The test passed.
Floor 13 Posted 2006-12-28 21:29 ·  中国 辽宁 联通
银牌会员
★★★
Credits 1,212
Posts 464
Joined 2006-12-13 21:11
19-year member
UID 73417
Gender Male
Status Offline
Floor 14 Posted 2007-02-18 04:43 ·  中国 浙江 台州 路桥区 电信
高级用户
★★
DOS学徒
Credits 526
Posts 252
Joined 2007-02-12 05:35
19-year member
UID 79286
Gender Male
Status Offline
Forum Jump: