(Reproduced) script

xiaoxiao2021-03-06  51

Script is transpired by:

http://www.microsoft.com/china/technet/archives/columns/scripts/sg1102.asp

Run WMI scripts on multiple computers

Scripting expert group

This page main title:

Briefly review the input computer name input to command line parameters to retrieve computer names from the text file from the text file from the Active Directory container from the text file.

Before the theme of this month, the script expert group said sincere gratitude to you! Our newly opened script programmers have been flooded by the floods, and can receive a reply from such a reader. The reply is definitely an exciting thing. Even if we are not allowed to answer each email from you (although we strive to reply as many emails as possible), we sincerely look forward to helping us maintain the right direction of development. Here again here sincere gratitude.

We will explore specific ways to modify the typical WMI scripts obtained from the script center, and to ensure that these scripts implement the revision method of running the multi-computer implementation. We have always emphasized a major advantage to these WMI scripts - they are mainly designed to rely on local computers to achieve operation - it can be easily adjusted to rely on a series of specified computer devices to implement operation.

This is indeed a very obvious advantage, but as we know, "light and easy" is a relatively strong statement; after all, unless someone professor you specifically realize the method, there is no "light and easy" in the scripting program. Say. In view of the fact that we have not yet started to show the specific implementation in front of you, so we received a lot of problems with the typical representatives:

"If I have written a script that is available to all operations based on the remote computer to query, can I use the same script to guide me into the remote computer name in the command line mode?"

"Does there is a valid approach to these scripts to rely on a computer implementation running, is there any possibility of obtaining a computer name from a file or other object?"

"Can you make this script to implement all domain controllers?"

The answer to the above question is only one: Of course you can. Please keep this straightforward answer in mind and let us start this month's column discussion.

Brief review

The best way to learn script preparation methods is to prepare a related script. To do this, let us start from an example script from the center of the script, which is mainly displayed by the WMI to display all the service functions that have been installed on the local computer. Beginning the script to make sure that it enables the operation of other devices other than the local computer, let us find out what it appears in the script center:

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2")

Set colrunningservices = objwmiservice.execQuery_

("Select * from win32_service")

For Each ObjService in ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

If you are not very familiar with the WMI script, then the above-mentioned code seems to have some puzzle. If you do have this, you can choose one from the following two entry methods. If you are willing, you can immediately go to the MSDN website and review the WMI entry series articles provided by the script clinics; when you completely immerse the WMI script programming the heavens and the earth, you can re-picked up this column article to temporary The content (please don't worry, I will wait patiently at this time). In addition, you can deliver trust to us, and we will provide you with a concise overview of the contents involved herein. Of course, you can study the WMI introductory article later in order to learn more details. Regardless of the learning method you take, we will start to explain the working principle of the above scripts from here. This part of the above script is related to WMI. More specifically, this code line is related to an object called namespace: the root / cimv2 namespace.

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2")

It is necessary to explain again. If you want to know more details, you should check the MSDN website. In short, this part of the script can connect you to WMI services based on a computer that has been assigned to the STRComputer variable (we will then introduce).

Description: So, what is the namespace? You can perform actions for objects called "class" in WMI. The class is a virtual appearance of true, vivid things; for example, there is a Win32_Service class that is available on a computer to refer to all services. Namespaces are available to store a simple location of a set of classes; in this case, the Win32_Service class is stored in the root / cimv2 namespace.

So what does the computer name mean? We just talked about the computer name being stored in the strComputer variable. However, the change has been set to a dot (.). Say, who will name your computer as a dot?

Ok, maybe no one will do this. However, in WMI, the approach to setting computer names as a dot is only to refer to a simplified manifestation of "local computers" under the premise of being limited to a particular local computer. Suppose you have a separate computer that has been named TestComputer. In this case, any line of the following two lines can guide you the local computer that is named TestComputer:

StrComputer = "."

Strcomputer = "testcomputer"

In fact, if the TestComputer IP address is 192.168.1.1, then the following line code can work:

Strcomputer = "192.168.1.1"

As mentioned earlier, we have used the code to write the computer name to the script. For example, the following line code is mainly used to connect to the WMI service named HRSERVER01:

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! // HRSERVER01 / ROOT / CIMv2")

In this case, why do we not simply write the above name directly to write a script? We do this, just to facilitate the operation of any computer to run the relevant script, and all the operations we must perform is only modified for the StrComputer variable. This is precisely the discussion of this column articles. The next part of the sample script will require WMI services to provide some information. It will send a series of requests for all services that have been installed in the specified computer and save relevant information to the ColrunningServices variable on this basis. (If you want to leave a deep impression on your friends, please tell them that ColrunningServices actually belongs to a special variable type called an object reference. But in this way, we can only want them to ask them no longer ask. "What is Object reference ", because we have no time to discuss this problem in depth.)

Set colrunningservices = objwmiservice.execQuery_

("Select * from win32_service")

The last part of the sample script is for use only for each service name that has been saved in the ColrunningServices variable and its status:

For Each ObjService in ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

Let us continue to type a full script code into notepad and save it as ListServices.vbs. Although you are actually insignificant for the stored position specified for this script, since we discuss around the same page, we should save the respective scripts to the C: / scripts directory. If there is no C: / scripts directory that has not been present on your computer, you should create this directory before performing the script save operation.

A free tip provided by the script expert group: Please note that there is a program method that can truly impress your friend; the following scripts will create a C: / Scripts folder for you:

Set objfso = creteObject ("scripting.filesystemobject")

Objfso.createfolder ("C: / scripts")

Once you have a script save operation, open a command line form and navigate to the C: / scripts directory, then run the script by entering the following command and tap the Enter key: Run the script:

Cscript listServices.vbs

You will see the script output as shown below, which shows all services based on local computers, and current status information for each service (such as "stop" or "run").

If the browser you are using unable to support the Embedded Frame, click here to browse in a separate page.

Now, everything is in a normal state, but if you want to get the same service information from a remote computer, what will I do? You may remember that we have set the strComputer variable to refer to a dot (.) Of the local computer in the first row of the script. In the subsequent section of the script, StrComputer is used to establish a connection to the WMI service based on the specified computer. In this way, the information retrieved by the script will be information about the remote computer, and independent of the computer running the script.

For example, suppose you need to modify the script use to establish a connection with a remote computer named HRSERVER01. To achieve the above purposes, you only need to change the strComputer variable value from "HRSERVER". If you are using your own computer at home, please select a remote computer from your network system and replace the dots in the assignment statement to the selected computer name. Note that in the default, you must be from a local administrator group that belongs to a remote computer to ensure that the script is running normally. This is mainly because only the local administrator group members have the ability to retrieve relevant information from the remote computer. For example, the following is a new script that can be retrieved from the computer named HRSERVER01:

strComputer = "HRSERVER01"

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2")

Set colrunningservices = objwmiservice.execQuery_

("Select * from win32_service")

For Each ObjService in ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

Please run the script that has been modified with the previously identical method, that is, enter the following command in the command line form. Tap the Enter key:

Cscript listServices.vbs

You should see the results similar to the previous script (the actual results you see may be different from services that have been installed on the remote computer).

If the browser you are using unable to support the Embedded Frame, click here to browse in a separate page.

The key difference between the above scripts with the first script we have written is that the services listed by the former will be objects running based on the remote computer HRSERVER01. For example, you may have noticed that a local computer running application management service (see the previous screen snapshot) has been terminated on a computer named HRSERVER01.

Description: If you have selected a computer that does not exist, or the selected computer is currently in an offline state, and will it be like? In this case, the script will crash. To do this, modify the first line of code in the script to "ON Error Resume Next" (if an error occurs, proceeding to subsequent code) to provide a temporary work area. Later, we will discuss with better solutions for this issue.

Enter the computer name as command line parameters

The way to modify the strComputer variable is indeed; it will allow you to run the relevant script on a remote computer. However, if you don't have to make a corresponding modification of this script for ensuring that the script relying on your computer, you will make things more perfect. In fact, if you specify a computer name as a command line parameter, things can also become more perfect.

This can sound some difficulties, but actually quite simple and easy. Whenever you start a script from a command line (for example, by entering the CScript ListServices.vbs command), any characters typed after the script name will be interpreted as command line parameters. In fact, these characters will not only be interpreted as command line parameters, but also they will be automatically retrieved and saved to ensure that you can access its implementation from the script. For example, it is assumed that you start a script by entering the following command:

Cscript listServices.vbs HRSERVER01 WebServer01

You can reference the first parameter (HRSERVER01) in the script and reference the second parameter (WebServer01) by means of WScript.Arguments (1). If there is still a third parameter, use WScript.Arguments (2) to reference. This method can be applied to several parameters in order. When you start a script when you use the command line parameter, you must also separate each parameter with at least one space.

Description: If you must enter a parameter (for example, default domain policy) containing spaces, how should you be? In this case, you must enclose the parameters you need to use in quotation marks, for example, "Default Domain Policy". If you do not use quotation marks, string default domain polic will be interpreted as three independent parameters: default, domain, and policy.

Let us try to handle as simple as possible: First, modify our script to ensure that it is running with any computer that we specify as the command line parameters. To achieve the above object, we only need to set the StrComputer variable to a state equal to the first command line parameter wscript.arguments (0). That is:

Stripomputer = wscript.arguments (0)

WScript.echo "Running Against Remote Computer Named:" & strComputer

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2")

Set colrunningservices = objwmiservice.execQuery_

("Select * from win32_service")

For Each ObjService in ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

Note: We also added a code to display the code of the computer name relying on the script to help you understand the script currently running.

First modify the script, try running it. Please note that if you try to run the script by previously taking the script - just enter the cscript listservices.vbs command, you will see the following error message:

C: /scripts/listservices.vbs (1, 1) Microsoft VBScript Runtime Error:

Subscript out of ing.

Why do this happen? Because you don't enter the command line parameters after the file name listServices.vbs, the reference to WScript.Arguments (0) does not have any meaning; you have told scripts to set the strComputer variable to the first parameter value, but There is no discovery related parameters. In this way, VBScript will cause you to fall into a dilemma. (By the way, (1, 1) will tell you about the script code line number of the VBScript language error.) Let us try to exclude errors identified by the VBScript language by entering the following command (you can Replace HRSERVER01 with a real computer name on your own network system):

Cscript listServices.vbs HRSERVER01

(If you only have a computer, you can enter this computer's name. And more convenient methods are, enter a dot and check whether the script relies on the local computer - we believe that this method is certain Effectiveness.)

You should review the current state of the service list and related services again. The main difference is reflected in that you only need to enter the appropriate name in the command line status, you can rely on any computer to run the relevant script. It can be seen that you have implemented the above purposes. Thank you for your cooperation and wish good night.

Enter multiple computer names as command line parameters

So far, we have not touched the problem that has been resolved in this column article: Run the relevant scripts in multiple computers. The aforementioned script is indeed relying on multiple computers - as long as you are willing to run multiple times. For example, you can list the service items on three different computers by entering the following commands: WebServer01, FileServer01, and SQLServer01.

Cscript listServices.vbs Web Server01

Cscript listServices.vbs FileServer01

Cscript listServices.vbs SQLServer01

But you are correct: This method of repeated input is too cumbersome for scripting programmers. Why don't we only enter a command like this to overcome the repetition problem?

Cscript listServices.vbs Web Server01 FILESERVER01 SQLSERVER0

We are of course done. As I said earlier, the command line parameters will be included in the collection of WSHARGUMENTS. The WSHARGUMENTS collection is merely a collection constructed by the command line parameters entered during the script run.

So, what help is it for us? We can retrieve each parameter from the WSHARGUMENTS collection using the FOR Each cycle statement (name). Here is a script that can be implemented by each computer that is dependent as a command line parameter:

For Each Strargument in wscript.arguments

Strcomputer = struntument

Wscript.echo "***** computer ******" & vbcrf & strcomputer & vbcrlf

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2")

Set colrunningservices = objwmiservice.execQuery_

("SELECT * WIN32_SERVICE") for Each ObjService In ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

NEXT

The functions of the above scripts are as follows:

This script will intercept command line parameters - is also the Webserver01, FILESERVER01, and SQLServer01 in this example - and save them to WSHARGUMENTS collections. This script will intercept the first parameter (webserver01) value and assign it to the StrComputer variable. This script is available to establish a connection with the computer that is referred to by the StrComputer variable, and performs retrieval and display operations for information related to all services. This script can be traced back to the FOR EACH loop start point and intercept the second parameter (FILESERVER01) value, and give it a StrComputer variable. This script is available to establish a connection with the computer that is referred to by the StrComputer variable, and performs retrieval and display operations for information related to all services. This script can be traced back to the FOR EACH loop start point and intercept the third parameter (SQLServer01) value - push it again. This script executes the cyclic program step in the week until the entire command line parameter collection is traversed.

By the way, the operations performed for the third parameter are not very rare. You can make the first, second, third and even 100 parameters such as the method. As long as the parameters you provide are not less than 1, this line code can work properly.

Description: How do some people forget to provide the required parameters in the program code? If you are worried about this, you should add the following code at the beginning of the script. This code mainly uses the count attribute of the WSHARGUMENT object to calculate the number of parameters contained in the collection. If the count property is assigned 0, it means that the programmer does not provide any parameters, so the script will terminate after displaying a prompt message:

IF wscript.arguments.count = 0 THEN

Wscript.echo "You Must Supply At Least One Computer Name."

WScript.quit

END IF

Retrieve computer name from text files

At the beginning of this column, we mainly develop a WMI script that is provided by the TechNet Script Center to retrieve service information related to a single computer: that is, the computer relying on the service function. We are now able to enter any number of different computer names to the command line while running the script, while the resulting run results are serviced from these computers.

Explanation: The information obtained by this method will make you need more. In subsequent release columns, we will introduce you to a specific way to save such information as a variety of formats; however, we can only use the redirect symbol (>) to guide the script output to a certain Text file (instead of a papers). Thereafter, you can also use Notepad to open the text file saved with the script output, and browse the file content as you want (you don't have to view under the glaring screen scrolling). To run the relevant script, and guide the running result to a text file called Report.txt, enter the following command under the command line mode:

Cscript listservices.vbs Webserver01 FILESERVER01> Report.txt

We can guess what you think now. You are thinking, "I should thank the script expert group, but I have to rely on 50 computers to run the script you have written. You can tell me how to enter this 50 computer name while running the script? "This idea certainly cannot be realized. But you can request your own script to perform a read operation for a text file saved with a computer name, and on this basis, relying on the implementation of each computer contained.

To achieve the above object, you should first be generated into a simple text file containing a computer name; in this file, each computer name will occupy a line. For convenience, save this file as c: /scripts/computers.txt.

If the browser you are using unable to support the Embedded Frame, click here to browse in a separate page.

The following code is a script that can be used to perform read operations for the aforementioned text file. When running this script, you will not have to use any command line parameters, just enter the following command in the command line mode, and tap the Enter key:

Cscript listServices.vbs

Const Input_file_name = "c: /scripts/computers.txt"

Const for_reading = 1

Set objfso = creteObject ("scripting.filesystemobject")

Set objfile = objfso.opentextfile (Input_file_name, for_reading)

Strcomputers = Objfile.readall

Objfile.close

ArcrComputers = Split (Strcomputers, VBCRLF)

For Each Strcomputer in ArrComputers

Set objwmiservice = getObject ("WinMgmts:" _

& "{ImpersonationLevel = Impersonate}! //" & strComputer & "/ root / cimv2")

Set colrunningservices = objwmiservice.execQuery_

("Select * from win32_service")

For Each ObjService in ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

NEXT

The operation results of the above scripts will be embodied, and the service information managed by the full computer that has been listed in the text file is displayed. It can be seen that we have received a program script available to implement the target operation; now, we will focus on the role of the script.

As you can see, the first two rows of this script are mainly used to set relevant constants aimed at making it more convenient to read and ideal. INPUT_FILE_NAME holds a text file path that contains a computer name. And for_reading is used to declare the need to read the needs of related information when opening files. We will introduce file operation methods in subsequent release columns; but you only need to know, you can perform read operations on text files, and perform write operations for such files. In view of you unable to perform read and write operations, you must indicate the mode of operation required in the script.

Another free trick provided by the script expert group: If you can't touch your friends below, you should consider paying a new friend. Please modify the first line of the above script to:

Input_file = wscript.arguments (0)

Do you have any benefits? Ok, suppose you have multiple text files that contain computer names: where one is related to your DHCP server, one is related to your domain controller, and is related to your email server. Do you need to generate each other's independent program script for each of them? Of course there is no need. Drag and drop the desired text file to the script file icon (listServices.vbs) in Windows Explorer. Thus, the script uses the text file name as a parameter and is automatically performed on this file on this file. As soon as you try it, you will understand our intention. Code line: set objfso = createObject ("scripting.filesystemObject") will indicate that your script is prepared for processing related files. VBScript does not know how to process files; and alternative methods are a COM object as a auxiliary means. We use FileSystemObject in this example. This is a COM object with VBScript and Windows Script Host, and has a good text file read and write capabilities.

Code line: set objfile = objfso.opentextfile (Input_file_name, for_reading) is a very easy to understand statement. It is mainly used to open the access path name that has been saved in the input_file_name constant for performing a read operation. By the way, this is exactly what we use for constants. Below this line uses script code for the forced coding value 1, you can open a text file for the execution of the read operation, but the intuitiveness of the effect will be greatly reduced:

Set objfile = objfso.opentextfile (Input_file_name, 1)

Code line: strcomputers = objfile.readall is where the file content read operation actually occurs. The file content will receive the read operation with its complete face and is saved in the Strcomputers variable. The next row script is only available to turn off the current text file.

In this link, we are almost in a very familiar realm. When we use the command line parameters, it will end with the computer name included in a collection (this situation is quite common in system management scripting programming). We also use the for Each loop statement for all items contained in a particular collection. Different, we have included all the computer names in the strComputers variable this time; in fact, if you are willing to display the strComputes variable value, it will get the results similar to the output of the text file. Unfortunately, this is not a collection, and we can only rely on the for Each loop statement and look forward to obtaining a reasonable run.

Code line: arrComputers = SPLIT (STRComputers, VBCRLF) is mainly used to intercept the content stored in the Strcomputers variable (computer name list), extract a single computer name, and placed them in an object called an array. The array is similar to the collection (although there is a major difference between the two, this difference is nothing to do only on the use of our set. It is important to use our old friends --for Each - the relevant array is traversed.

You may also want to know how the SPLIT function will distinguish between the computer name stored in the strComputes variable. As you remember, each computer name occupies a separate line in a text file. In such text files, each line is not visible with a VBScript called VBCRLF (ie, the carriage return) ends. We basically inform the SPLIT function, and the strCompute variable corresponding to a single project will be separated by the return line identifier. For example, the function will first find the string HRSERVER01, and then the carriage return is encountered. And this is just the first project - HrServer01 - there is a sign of discovered. The SPLIT function will put the computer name HRSERVER01 into the array and continue to perform the read operation. Next, the function will also discover the string WebServer01, and then encounter a return line mark. Push it according to next time, you will be able to enliminate the rest of the processing process. After setting the relevant computer name into the array, the functionality of the script remaining is not different before the modification. It only performs retrieval operations on the entire computer name in the array (set) with the FOR Each cycle statement. The results of the script run are displayed for related service information on each computer.

Retrieve computer name from the Active Directory container

Due to the satisfaction of the above harvest, it is not very different from crime (of course, you don't have to pick up the phone call 9-1-1 alarm station). We do have a fairly excellent solution. Of course, please also think about the specific implementation of these computer names to place these computer names. If you are currently in an Active Directory-based environment, you may call the Active Directory Users and Computers feature and check for the relevant directory. But after all, it is a script programmer! Why do you have to engage in this manual labor? Don't you indicate that the script will do the above work? You should of course be. Microsoft companies have provided you with the required script library: Active Directory Service Interface (ADSI).

ADSI will allow the script you have written to talk to directory services similar to Active Directory. However, the principle of working principle of ADSI has been explained by this discussion. In other words, if you do not explain the specific implementation of the computer name with the ADSI support characteristics directly from the relevant directory, this article is not comprehensive enough. Therefore, we will provide you with a more light explanation through an example script and to open a special book that Microsoft Press is about to publish. This entrained in the Microsoft Windows 2000 Script Programming Guide will be detailed around the ADSI (please don't worry, we are not a group of sales in a huge pressure; we will provide this professional work through online way to help you save Go down to buy X-Box.)

The following is an example script used to implement the above purposes. This script mainly uses ADSI to adhere to the Computers container in the Fabrikam.com domain, and can intercept all the computer names stored in this container into a collection. When the above tasks are completed, the remainder of the script will use the for Each loop speech to traverse specific collections, and collect relevant service information during this process.

SETOBJECT ("LDAP: // CN = Computers, DC = Fabrikam, DC = COM")

For Each Objcomputer in Colcomputers

Strcomputer = Objcomputer.cn

Set objwmiservice = getObject ("Winmgmts:" _ & "{impersonationLevel = impersonate}! //" & struct ")

Set colrunningservices = objwmiservice.execQuery_

("Select * from win32_service")

For Each ObjService in ColrunningServices

Wscript.echo objservice.displayname & vbtab & objservice.state

NEXT

NEXT

What is better if the computer account you use is not stored in the Computers container? No problem; you can modify the string "LDAP: // CN = Computers, DC = Fabrikam, DC = COM" to establish a connection with other containers in the relevant directory. For example, the following code line can be used to establish a connection to the Finance OU (note that you must use the grammar format of the ou =, not CN =):

SET Colcomputers = getObject ("ldap: // ou = finance, dc = fabrikam, dc = com")

转载请注明原文地址:https://www.9cbs.com/read-87463.html

New Post(0)