Vbs utility self-built-Windows Script application instance

Source: Internet
Author: User
Tags access properties microsoft outlook

Since the Windows 98 era, various script files have emerged constantly. script files are used to directly run various script files on the Windows interface or Dos command prompt, microsoft implanted a 32-bit Windows-based, independent script running environment in the system and named it "Windows Scripting Host (WSH for Windows Script Host )".
After WSH was born, it was quickly promoted in the Windows series. In addition to Windows 98, Microsoft has embedded WSH in Internet Information Server, Windows ME, Windows 2000, Windows XP Professional, and other products. In general, most people's habits and needs are always taken into account for various software, while general-purpose software is difficult to meet some Personalized Requirements. Now we can use WSH to complete a lot of interesting and practical functions, and the implementation code is very simple, and it is completely customized for ourselves, 100% to meet their own needs. How can this simple, practical, and interesting thing be avoided?
I. How does WSH work?
The precondition for WSH to work properly is that IE3.0 or later must be available in the system, because WSH needs to use VBScript and JScript interpretation engine in IE during work.
First, let's take a look at the simplest example. Open notepad and write down:
WScript. Echo ("Hello! Computer ")
Then. vbs or. js is a file with a suffix (do not save it as a TXT file, select "all files" in "file type" when saving), and then close this notepad. The file icon shows that it has changed to a script file. Double-click to execute the file and check the result. (1) The first script We edited has been successfully run!
Figure 1
Now let's take a look at the process of running the script file via WSH. First, WSH queries the required script engine in the system registry based on the script file suffix, such as VBScript or JScript. Then run the script command using the corresponding script engine. Some script commands use the WSH built-in object (such as the registry key). Then, the script command sends a request to WSH, and WSH completes these commands.
So, how to write and run the WSH script? You can use any text editor to compile WSH script files. After writing, you only need to save it as the file name supported by WSH (for example. js files ,. vbs file ). The most common editor is the Notepad used to compile the first script file.

I. WSH preliminary
Next, let's take a look at some preliminary WSH instances. Each instance can implement a simple function. After we understand the features of each instance, we will combine these examples into a very practical script to help you implement practical and personalized powerful functions.
1. create shortcuts on the desktop
WSHShell = WScript. CreateObject ("WScript. Shell ");
Export toppath = WSHShell. SpecialFolders ("Desktop ");
Shortcut1 = WSHShell. CreateShortcut (export toppath + "\ notepad shortcut. lnk ");
Shortcut1.TargetPath = "c :\\ Windows \ notepad.exe ";
Shortcut1.Save ();
The SpecialFolders function is used to read the desktop path. After obtaining the desktop path, create a "\ Users local file. lnk.pdf file on the desktop, and direct the target of this square file to notepad.exe. Finally, save the information. The script is complete.

2. Execute specific commands
In the following example, open the "C: \ autoexec. bat" file in notepad and open the DOS command window (and list the results of executing dir c: \ Windows). The program code is as follows:

// Generate WSH Shell
Shell = WScript. CreateObject ("WScript. Shell ");

// Enable notepad and load c: \ autoexec. bat
Shell. Run ("notepad.exe c: \ autoexec. bat ");

// Open the DOS command window and execute dir c: \ Windows
Shell. Run ("cmd/K dir c: \ Windows ");

In the preceding example, the enabled application remains open, and WSH continues to execute the subsequent program code. If you want to continue executing the WSH program code after the application is closed, you can add other parameters after run. What should we do if we need to stop executing Notepad?

// How to run other applications by WSH, and continue to execute WSH program code after the application ends
Shell = new ActiveXObject ("WScript. Shell ");
IntReturn = shell. Run ("notepad" + WScript. ScriptFullName, 1, true );
Shell. Popup ("Notepad has been closed! ");

3. list all objects in a specific directory
// Create a file system object
Fso = new ActiveXObject ("Scripting. FileSystemObject ");
// Point to the specified folder
Dir = "c: \ Windows \ temp ";
Fsofolder = fso. GetFolder (dir );
// Collect the files contained in the folder
ColFiles = fsofolder. Files;
Fc = new Enumerator (colFiles );
// Display and continue reading the file name of other files until it is completed
WScript. Echo ("Files under \" "+ dir + "\":");
For (;! Fc. atEnd (); fc. moveNext ()){
WScript. Echo (fc. item ());
}
After the script is executed, all files in the specified directory (C: \ windows \ temp) are listed one by one.

4. display the local IP Address
Ws = new ActiveXObject ("MSWinsock. Winsock ");
WScript. Echo ("the local IP address is:" + ws. LocalIP );
Use the MSWinsock. Winsock function to collect and display IP addresses.

5. List disk drives and their related properties

Fso = new ActiveXObject ("Scripting. FileSystemObject ");
DriveTypeNames = ["unknown type", "removable disk", "Hard Disk", "Network Disk Drive", "cd", "Virtual Disk"];
E = new Enumerator (fso. Drives );
S = "";
For (;! E. atEnd (); e. moveNext ()){
X = e. item ();
WScript. Echo (x. DriveLetter + ":")
WScript. Echo ("disk type:" + x. DriveType + "(" + driveTypeNames [x. DriveType] + ")");
WScript. Echo ("Share Name:" + x. ShareName );
WScript. Echo ("disk ready:" + x. IsReady );
If (x. IsReady ){
WScript. Echo ("volume label:" + x. VolumeName );
WScript. Echo ("Space size:" + x. AvailableSpace + "Byte ");
}
}
After the script is executed, the disk drive type, volume label, space size, shared name, and other information are displayed.

6. display the current time
Today = new Date ();
WScript. Echo ("Computer fans report to you:" + today. toLocaleString ());
In addition to this method, there is also a more complex method that can display the last and afternoon time
Function getTime (){
Today = new Date ();
Hour = today. getHours ();
Minute = today. getMinutes ();
Second = today. getSeconds ();
Prepand = (hour> = 12 )? "Afternoon": "Morning ";
Hour = (hour> = 12 )? Hour-12: hour;
Str = "the current time is" + prepand + hour + "point" + minute + "minute" + second + "second ";
Return (str );
}
WScript. Echo (getTime ());

7. Save the current webpage
// Capture a webpage and save its content to a file
Inet = new ActiveXObject ("InetCtls. Inet ");
// Download URL
Inet. Url = "http://www.pcfans.net/index.htm ";
// Set timeout
Inet. RequestTimeOut = 20;
// Download an object
WScript. Echo ("Downloading \" "+ inet. Url + "\"...");
Content = inet. OpenURL ();

// Write a file
Fso = new ActiveXObject ("Scripting. FileSystemObject ");
ForReading = 1, forWriting = 2;
FileName = "test.htm ";
Fid = fso. OpenTextFile (fileName, forWriting, true );
Fid. Write (content );
Fid. Close ();
WScript. Echo (the content captured from "+ inet. Url +" has been saved to "" + fileName + "」! ");

8. List important environment variables related to SYSTEM
Shell = WScript. CreateObject ("WScript. Shell ");
EnvObj = shell. Environment ("SYSTEM ");

WScript. Echo ("======= list of all SYSTEM environment variables :");
WScript. Echo ("No. of env. variables =" + envObj. length );
Var Enum = new Enumerator (envObj)
For (Enum. moveFirst ();! Enum. atEnd (); Enum. moveNext ())
// WScript. Echo (Enum. item () + "==>" + envObj (Enum. item ()));
WScript. Echo (Enum. item ());
Have you read the "System" attribute? Do I need to manually check the system environment configurations in the attributes? This script can solve this series of problems.

9. scripts for automatically reading letters from Outlook Express
Var profile = "Microsoft Outlook Internet Settings ";
Omapi = new ActiveXObject ("MAPI. Session ");
Omapi. Logon (profile );
ObjFolder = omapi. Inbox;
ObjMsg = objFolder. Messages;
MyMsg = objMsg. GetFirst ();
Msg = myMsg. Text;
WScript. Echo (msg );
For (I = 0; I <10; I ++)
{
MyMsg = objMsg. GetNext ();
Msg = myMsg. Text;
WScript. Echo (msg );
}
This script can automatically find the last 10 emails received from the mail of Outlook Express, so that you can quickly read the emails without opening Outlook.

10. view detailed attributes of a file
Var file = "results.html ";
// Create a file system and obtain the file
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var f = fso. GetFile (file );
// Access properties and format results.
Var fileinfo = "Results for" + file + "\ n ";
Fileinfo + = "Name:" + f. Name + "\ n ";
Fileinfo + = "attribute:" + f. Attributes + "\ n ";
Fileinfo + = "Size:" + f. Size + "Bytes \ n ";
Fileinfo + = "created on:" + f. DateCreated + "\ n ";
Fileinfo + = "last access date:" + f. DateLastAccessed + "\ n ";
Fileinfo + = "last modification period:" + f. DateLastModified + "\ n ";
Fileinfo + = "Drive:" + f. Drive + "\ n ";
Fileinfo + = "Type:" + f. Type + "\ n ";
// Display the result
WScript. Echo (fileinfo );

Use this function Scripting. fileSystemObject, we can view the detailed attributes of a file. If the file to be viewed is not in the same directory as the script, we need to enter the complete file path name for viewing. In addition, this script needs to be used through the command line.
The method for running in DOS is as follows: in the DOS command line window, enter "cscript // <script file name>" or "wscript // <script file name>" to get the running effect.

11. Customize compressed files
WinRAR is a popular compression program. After installing WinRAR, you must first add a relative path for running WinRAR, which is similar to the path added to the executable file in the config. sys file in DOS. After "set path = c: \ Windows; c: \ program files \ WinRAR" is added to the system environment variable, you can directly call WinRAR. For the use of winrars' command line, you can enter "cmdrar.exe/?" In the DOS window or command line window /?" You can get help.
After preparing WinRAR, you can use the following script to complete custom compression.

Set WshShell = Wscript. CreateObject ("Wscript. Shell ")
WshShell. Run ("c :\\ rar.exe c :\\ test.rar c :\\ a.txt c :\\ B .txt ")
<Script language = "VBScript. Encode" runat = server>
Set WshShell = server. CreateObject ("Wscript. Shell ")
IsSuccess = WshShell. Run ("c :\\ rar.exe c :\\ test.rar c :\\ a.txt c :\\ B .txt", 1, true)
If IsSuccess = 0 Then
Response. write "Command executed successfully! "
Else
Response. write "command execution failed! Insufficient permissions or the program cannot run in DOS state"
End if
</Script>
Ii. Comprehensive Application
In our opinion, there are so many separate examples. Now we can slightly modify and combine the above script to make it a very convenient tool. It can implement the following functions:
1. automatically clear temporary files.
2. Automatic Backup of documents, including files in my documents and emails in Outlook Express.
3. for backup files, compression is required, and the compressed files are named by date and placed in the specified location.
4. Generate a backup report.
5. automatically shut down after completion.
The following code implements the above functions:
// Step 1: copy itself to C: and create a shortcut on the desktop
WshShell = WScript. CreateObject ("WScript. Shell ");
Str = "\" "+ WScript. ScriptFullname +" \ "c: \ shutdown. js"
WshShell. Run ("cmd/c copy" + str, 0); // copy the whs script to c: \ shutdown. js.
Export toppath = WshShell. SpecialFolders ("Desktop"); // obtain the actual Desktop path
Shortcut1 = WshShell. CreateShortcut (export toppath + "\ shutdown. lnk"); // start creating a shortcut
Shortcut1.TargetPath = "c: \ shutdown. js ";
Shortcut1.Save ();

// Step 2: Clear the temporary folder of the user
EnvObj = WshShell. Environment ("USER ");
Tmp = WshShell. ExpandEnvironmentStrings (envObj ("TMP"); // obtain the actual path of your Temporary Folder
Temp = WshShell. ExpandEnvironmentStrings (envObj ("TEMP"); // obtain the actual path of your Temporary Folder

Fso = new ActiveXObject ("Scripting. FileSystemObject ");
// Fso. DeleteFolder (tmp, true); // start to delete (if the Temporary Folder system is in use, deletion will fail !)
// Fso. DeleteFolder (temp, true );

Tip: You can add other folders to be deleted to meet your actual needs.

// Step 3: // create a backup folder with the suffix of time
Var newDate = new Date ();
Bakfolder = "c: \ bak _" + newDate. getYear () + "year" + (newDate. getMonth () + 1) + "month" + newDate. getDate () + "day _" + newDate. getHours () + "Hour" + newDate. getMinutes () + "Minute" + newDate. getSeconds () + "seconds ";
Fso. CreateFolder (bakfolder );

Tip: You can also directly specify a fixed folder to put the backup file in a fixed folder.

// Step 4: Start to call WinRAR for backup and directly compress the compressed file generated by the backup folder into the backup folder you just created.
// First obtain the folder to be backed up: My documents and Outlook Express storage folder
// The folder for storing Outlook express varies with the sub-accounts of each machine. Use the following method to obtain it:
// Open Outlook express and select Tools \ options \ Maintenance \ storage folder from the menu
Mydoc = "\" "+ WshShell. SpecialFolders (" MyDocuments ") +" \ "; // obtain the actual path of my document
Outlook = "\" C: \ Documents and Settings \ netbee \ Local Settings \ Application Data \ Identities \ {7F935084-E34D-4E22-86E9-10D00355B59D} \ Microsoft \ Outlook Express \"";
// Start the compression and backup process
IsSuccess = WshShell. Run ("WinRAR.exe a-r \" "+ bakfolder +" \ doc.rar \ "" + mydoc, 1, true );
// IsSuccess = WshShell. Run ("WinRAR.exe a-r \" "+ bakfolder +" \ Outlook.rar \ "" + Outlook, 1, true)

Tip: You can add other directories to be backed up to meet your needs. In addition, if you change the Backup Directory to a fixed directory in the previous step, you can use the WinRAR command line parameter to implement Incremental backup of the backup file to avoid occupying space for each shutdown backup. Due to space limitations, we will not list the relevant command parameters of WinRAR here. Please refer to the WinRAR help file on your own.
// Step 5: Create a report in the backup folder, including the backup date and time, backup file name, and backup file size. Finally, the report content is displayed.
Reportfile = bakfolder + "\ repot.txt ";
Tf = fso. CreateTextFile (reportfile, true );
Tf. WriteLine ("************** backup report **************");
Tf. WriteLine ("backup date:" + newDate. toLocaleString ());
Tf. writeLine ("My document backup file name:" + bakfolder + "\ doc.rar file size:" + fso. getFile (bakfolder + "\ doc.rar "). size + "Byte ");
// Tf. writeLine ("Outlook backup file name:" + bakfolder + "\ Outlook.rar file size:" + fso. getFile (bakfolder + "\ Outlook.rar "). size + "Byte ");
Tf. WriteLine ("---------------------------------");
Tf. WriteLine ("close this file and start to close the computer ");
Tf. Close ();
WshShell. Run ("notepad.exe" + reportfile, 1, true); // display the Report Content
Tip: after a report is generated, the report is displayed on the screen. The shutdown operation will continue only when the user closes the report. If you need to shut down the instance directly, read the second instance in the first part of this article.

Finally, we want this script to be automatically executed when we log off or shut down, as long as the script is specified in the Group Policy to be used for logout. The specific method is to run "gpedit. msc open the Group Policy, select "Local Computer Policy/user configuration/Windows Settings/script-(login/logout)", and double-click "logout" to open the logout attribute, select "add", select Browse next to "Script Name", find our script and confirm, and close the Group Policy. Shut down now and try it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.