1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 7 ppsx

10 548 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 235,66 KB

Nội dung

40 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Object Description WshNamed This object provides access to a set of named command-line arguments. Properties: Item and Length. Methods: Count() and Exists(). WshUnnamed This object provides access to a set of unnamed command-line arguments. Properties: Item and Length. Methods: Count(). WshController This object provides the capability to create a remote script process. Properties: This object does not support any properties. Methods: CreateScript. WshRemote This object provides the capability to administer remote computer systems using scripts over a network. Properties: Status and Error. Methods: Execute() and Terminate(). WshRemoteError This object provides access to information on errors produced by remote scripts. Properties: Description, Line, Character, SourceText, Source, and Number. Methods: This object does not support any methods. WshNetwork This object provides access to a number of different network resources such as network printers and drives. Properties: ComputerName, UserDomain, and UserName. Methods: AddWindowsPrinterConnection(), AddPrinterConnection(), EnumNetworkDrives(), EnumPrinterConnection(), MapNetworkDrive(), RemoveNetworkDrive(), RemovePrinterConnection(), and SetDefaultPrinter(). WshShell This object provides access to the Windows Registry, event log, environmental variables, shortcuts, and applications. Properties: CurrentDirectory, Environment, and SpecialFolders. Methods: AppActivate(), CreateShortcut(), ExpandEnvironmentStrings(), LogEvent(), Popup(), RegDelete(), RegRead(), RegWrite(), Run(), SendKeys(), and Exec(). WshShortcut This object provides scripts with methods and properties for creating and manipulating Windows shortcuts. Properties: Arguments, Description, FullName, Hotkey, IconLocation, TargetPath, WindowStyle, and WorkingDirectory. Method: Save(). TABLE 2.2 WSH CORE O BJECTS ( CONTINUED) There are too many properties and methods supported by objects in the WSH core object model to include them all in this table. I will cover them separately a little later in this chapter. Examining Object Properties By accessing object properties, your scripts can gather all kinds of information when they execute. For example, using the properties associated with the WshNetwork object, your scripts can collect information about the Windows domain that the person who ran the script has logged in to, as well as the computer’s name and the user’s name. This information could then be used, for example, to prevent the script from executing on certain domains or computers. More than three dozen properties are associated with various WSH objects. In many cases, properties are associated with more than one object. Refer to Table 2.2 to see which proper- ties are associated with which objects. Table 2.3 provides a complete review of WSH object properties. 41 Chapter 2 • Overview of the Windows Script Host Object Description WshUrlShortcut This object provides scripts with methods and properties for creating and manipulating URL shortcuts. Properties: FullName and TargetPath. Method: Save(). WshEnvironment This object provides access to Windows environmental variables. Properties: Item and Length. Methods: Remove() and Count(). WshSpecialFolders This object provides access to special Windows folders that allow scripts to configure the Start menu, desktop, Quick Launch Toolbar, and other special Windows folders. Properties: Item. Methods: Count(). WshScriptExec This object provides access to error information from scripts run using the Exec method. Properties: Status, StdOut, StdIn, and StdErr. Methods: Terminate(). TABLE 2.2 WSH CORE O BJECTS ( CONTINUED) 42 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Property Description Arguments Sets a pointer reference to the WshArguments collection. AtEndOfLine Returns either true or false depending on whether the end-of-line maker has been reached in the stream. AtEndOfStream Returns either true or false depending on whether the end of the input stream has been reached. Character Identifies the specific character in a line of code where an error occurs. Column Returns the current column position in the input stream. ComputerName Retrieves a computer’s name. CurrentDirectory Sets or retrieves a script current working directory. Description Retrieves the description for a specified shortcut. Environment Sets a pointer reference to the WshEnvironment. Error Provides the ability to expose a WshRemoteError object. ExitCode Returns the existing code from a script started using Exec(). FullName Retrieves a shortcut or executable program’s path. HotKey Retrieves the hotkey associated with the specified shortcut. IconLocation Retrieves an icon’s location. Interactive Provides the ability to programmatically set script mode. Item Retrieves the specified item from a collection or provides access to items stored in the WshNamed object. Length Retrieves a count of enumerated items. Line Returns the line number for the current line in the input stream or identifies the line number within a script on which an error occurred. Name Returns a string representing the name of the WScript object. Number Provides access to an error number. Path Returns the location of the folder where the CScript or WScript execution hosts reside. ProcessID Retrieves the process ID (PID) for a process started using the WshScriptExec object. ScriptFullName Returns an executing script’s path. ScriptName Returns the name of the executing script. Source Retrieves the identity of the object that caused a script error. TABLE 2.3 WSH OBJECT P ROPERTIES Working with Object Properties Now let’s take a look at an example of a VBScript that demonstrates how to instantiate an instance of the WshNetwork object and access its properties. The script is called NetInfo.vbs and is as follows: Set WshNtwk = WScript.CreateObject(“WScript.Network”) PropertyInfo = “User Domain” & vbTab & “= “ & WshNtwk.UserDomain & _ vbCrLf & “Computer Name” & vbTab & “= “ & WshNtwk.ComputerName & _ vbCrLf & _ “User Name” & vbTab & “= “ & WshNtwk.UserName & vbCrLf MsgBox PropertyInfo, vbOkOnly , “WshNtwk Properties Example” As you can see, it isn’t a very big script. It begins by using a Set statement to create an instance of the WshNetwork object, which is associated with a variable name of WshNtwk. After you have established an instance of the WshNetwork object in this manner, you can reference the object’s properties and methods using its variable name assignment. 43 Chapter 2 • Overview of the Windows Script Host Property Description SourceText Retrieves the source code that created the error. SpecialFolders Provides access to the Windows Start menu and desktop folders. Status Provides status information about a remotely executing script or a script starting with Exec(). StdErr Enables a script to write to the error output stream or provides access to read-only error output from an Exec object. StdIn Enables read access to the input stream or provides access to the write-only input stream for the Exec object. StdOut Enables write access to the output stream or provides access to the write- only output stream of the Exec object. TargetPath Retrieves a shortcut’s path to its associated object. UserDomain Retrieves the domain name. UserName Retrieves the currently logged-on user’s name. Version Retrieves the WSH version number. WindowStyle Retrieves a shortcut’s window style. WorkingDirectory Returns the working directory associated with the specified shortcut. TABLE 2.3 WSH OBJECT P ROPERTIES ( CONTINUED) The next statement is so long, that to improve the script’s readability, I decided to break it into three lines and end each of the first two lines with the & and _ characters. The & character is a concatenation char- acter and is used to append two strings. The _ charac- ter is a continuation character and is used to indicate that a statement is continued on the next line. This statement displays the values of the following WshShell properties: • WshNetwork.UserDomain. The name of the domain into which the person running the script is logged in. • WshNetwork.ComputerName. The name of the computer on which the script is being executed. • WshNetwork.UserName. The username of the person who ran the script. To improve the presentation of the message, I formatted it using the VBScript vbTab and vbCrLf constants. The vbTab constant is used to line up the output at the point of the equals sign. The vbCrLf constant is used to execute a line feed and carriage return at the end of each line of output. The last thing that the script does is display the message using the following statement: MsgBox PropertyInfo, vbOkOnly , “WshNetwork Properties Example” MsgBox() is a built-in VBScript function that displays a text message in a pop-up dialog. PropertyInfo is a vari- able that I used to store the output message. VbOkOnly is a VBScript constant that tells the MsgBox() function to only display the OK button in the pop-up dialog. The last part of the previous statement is a message that will be displayed in the pop-up dialog ’s title bar. If you save and run this script yourself, you should see a pop-up dialog similar to the one shown in Figure 2.6. 44 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Definition The Set statement is used to create a reference to a specified object. Using this reference, you can refer to the object and its properties and methods over and over again throughout your script. Definition A constant is a VBScript construct that contains information that does not change during the execution of a script. VBScript provides a collec- tion of built-in constants, such as the vbTab and vbCrLf constants, that you can incorporate into your scripts to control the formatting of your script output. Examining Object Methods The WSH also provides a large collection of object methods. By using these methods in your VBScripts, you’ll be able to manipulate the Windows resources associated with objects. You won’t be able to do anything with your VBScripts that you don’t have the appropriate set of security permissions and rights to do on a particular computer. For example, if you don’t have the ability to manually create a new user account on your computer, then you won’t be able to run a VBScript designed to perform this operation, either. However, if you have administrative privileges on the computer, your scripts should be able to run unhindered. For example, using the WshShell object’s RegRead(), RegWrite(), and RegDelete() methods, you can create scripts that can access and manipulate the contents of the Windows Registry. Using these methods, you can create scripts that can configure just about any Windows resource. The Windows Registry is a repository used by the operating system to store information about every aspect of the computer’s hardware and software. Making an incorrect configuration change to the Registry can have disastrous effects on the operation of the computer and may potentially prevent it from being able to start. I strongly recommend that, unless you’re very sure of what you are doing, you never attempt to modify the Registry, either manually or by using a script. Table 2.4 provides a complete review of WSH object methods. TRAP TRAP 45 Chapter 2 • Overview of the Windows Script Host Figure 2.6 A pop-up dialog displaying properties associated with the WshNetwork object. 46 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Method Description AddPrinterConnection() Creates printer mappings. AddWindowsPrinterConnection() Creates a new printer connection. AppActivate() Activates the targeted application window. Close() Terminates or ends an open data stream. ConnectObject() Establishes a connection to an object. Count Retrieves the number of switches found in the WshNamed and WshUnnamed objects. CreateObject() Creates a new instance of an object. CreateScript() Instantiates a WshRemote object representing a script that is running remotely. CreateShortcut() Creates a Windows shortcut. DisconnectObject() Terminates a connection with an object. Echo() Displays a text message. EnumNetworkDrives() Enables access to network drives. EnumPrinterConnections() Enables access to network printers. Exec() Executes an application in a child command shell and provides access to the environment variables. Execute() Initiates the execution of a remote script object. Exists() Determines a specified key exists within the WshNamed object. ExpandEnvironmentStrings() Retrieves a string representing the contents of the Process environmental variable. GetObject() Retrieves an Automation object. GetResource() Retrieves a resource’s value as specified by the <resource> tag. LogEvent() Writes a message in the Windows event log. MapNetworkDrive() Creates a network drive mapping. Popup() Displays a text message in a pop-up dialog. Quit() Terminates, or ends, a script. Read() Retrieves a string of characters from the input stream ReadAll() Retrieves the s string that is made up of the characters in the input stream. TABLE 2.4 WSH OBJECT M ETHODS Working with Object Methods To really understand how object methods work, you need to work with some examples. Let’s take a look at two examples. In the first example, you’ll see how to work with the WshShell object’s Run() method to create a graphical front-end to the Windows NET SEND command. In the second example, you’ll learn how to use the WshShell object’s LogEvent() method to write messages directly to a Windows XP, .NET, 2000, or NT computer’s application event log. 47 Chapter 2 • Overview of the Windows Script Host Method Description ReadLine() Retrieves a string containing an entire line of data from the input stream. RegDelete() Deletes a Registry key or value. RegRead() Retrieves a Registry key or value. RegWrite() Creates a Registry key or value. Remove() Deletes the specified environmental variable. RemoveNetworkDrive() Deletes the connection to the specified network drive. RemovePrinterConnection() Deletes the connection to the specified network printer. Run() Starts a new process. Save() Saves a shortcut. SendKeys() Emulates keystrokes and sends typed data to a specified window. SetDefaultPrinter() Establishes a default Windows printer. ShowUsage() Retrieves information regarding the way that a script is supposed to be executed. Skip() Skips x number of characters when reading from the input stream. SkipLine() Skips an entire line when reading from the input stream. Sleep() Pauses script execution for x number of seconds. Terminate() Stops a process started by Exec(). Write() Places a string in the output stream. WriteBlankLines() Places a blank in the output stream. WriteLine() Places a string in the output stream. TABLE 2.4 WSH OBJECT M ETHODS (CONTINUED) 48 The WshShell object provides access to a number of Windows resources, including • The Windows application log • The Windows Registry • Any Windows command-line command Let’s look at an example of how to use the WshShell object’s Run() method. I’ve named this VBScript NetMessenger.vbs. NetMessenger.vbs provides a friendly graphical front end to the Windows NET SEND command-line command. The NET SEND command can be used to send text messages over a network to other currently logged-on users by specifying either the user’s username or the computer name that the user is using. To use this command from the Windows command line, you might type something like NET SEND jford Jerry, please stop by my office when you have a moment NET SEND is the command being used. Jford is the username of the person to receive the mes- sage, and the rest of the statement is the message text that is to be sent. Using the NET SEND command is not very complicated. Click on Start, Run, and then type CMD and click on OK. This opens the Windows Console. Now type the NET SEND command and press the Enter key. That’s it. Within moments, your message should appear on the recipi- ent’s screen. Unfortunately, many people are intimidated by the very thought of using the Windows command prompt. So let’s write a VBScript, shown here, that makes using this command easy: Set WshShl = WScript.CreateObject(“WScript.Shell”) Recipient = InputBox(“Type the username or computer name “ & _ “that the message is to be sent: “) MsgText = InputBox(“Type your message: “) WshShl.Run “Net Send “ & Recipient & “ “ & MsgText The first line of this script instantiates the WshShell object and associates with it a variable called WshShl. The next two lines display a pop-up dialog asking the user to type a username or computer name. The information typed in by the user is stored in a variable called Recipient. The next line allows the user to type in a text message and stores it in a variable called MsgText. The last line of this script executes the WshShell object’s Run() method, passing it the NET SEND command, the name of the recipient, and the message to be sent. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Open your script editor and type in the script as just shown, and then save it as Messenger.vbs. Run the script and you’ll see a pop-up dialog like the one in Figure 2.7, asking for the user- name or computer name of the recipient. Type the required information and click on OK. The pop-up dialog shown in Figure 2.8 appears. Type the message you want to send and then click OK. Within a few moments, your message appears on the recipient’s screen, as shown in Figure 2.9. In the second example, you’ll learn how to use the WshShell object’s LogEvent() method to write a message to the Windows event log. The Windows event log is accessed differently, depending on which version of Windows you use. For example, on Windows 2000 and Windows XP, you can click Start and then right-click My Computer and select Manage to open the Computer Management console where the Event Viewer utility or snap-in resides. To view the application event log, expand the Event Viewer node and select Application, as shown in Figure 2.10. Double-click on an event entry in the event log to examine it. 49 Chapter 2 • Overview of the Windows Script Host Figure 2.7 Type the username or computer name to which you want to send a message. Figure 2.8 Type the message that you want to send. Figure 2.9 The recipient of the message sees your message, as well as your computer’s name and the date and time of the message. . executes the WshShell object’s Run() method, passing it the NET SEND command, the name of the recipient, and the message to be sent. Microsoft WSH and VBScript Programming for the Absolute Beginner, . SEND is the command being used. Jford is the username of the person to receive the mes- sage, and the rest of the statement is the message text that is to be sent. Using the NET SEND command is. using the Exec method. Properties: Status, StdOut, StdIn, and StdErr. Methods: Terminate(). TABLE 2.2 WSH CORE O BJECTS ( CONTINUED) 42 Microsoft WSH and VBScript Programming for the Absolute Beginner,

Ngày đăng: 03/07/2014, 18:20

TỪ KHÓA LIÊN QUAN