VBS practical software Self-made--windows script application instance _vbs

Source: Internet
Author: User
Tags access properties current time rar microsoft outlook
Since the Windows 98 era, a variety of script files have been emerging, the role of script files in order to implement a variety of script files in the Windows interface or a Dos command prompt run directly, Microsoft embedded in the system based on a 32-bit Windows platform, a separate script operating environment, and name it "Windows Scripting Host (Windows Script Host hereinafter WSH)".
After the birth of WSH, it was quickly popularized in the Windows series. In addition to Windows 98, Microsoft has WSH embedded in products such as Internet information Server, Windows ME, Windows 2000 series, and Windows XP Professional. Generally speaking, a variety of software must take into account the majority of the habits and needs, and for some personalized strong demand, general-purpose software is difficult to meet. Now using WSH, we can accomplish a lot of interesting and practical functions, and the implementation of the code is very simple, and completely tailor-made for themselves, 100% to meet their needs. So simple and practical there are interesting things, how can you let go of it?
First, how does WSH work?
The prerequisite for WSH to work properly is that the system must have more than IE3.0 versions, because WSH needs to use the VBScript and JScript interpreter engines in IE when working.
First, let's take a look at one of the simplest examples, open Notepad, and write:
WScript.Echo ("Hello!") Computer ")
Then save it as a. vbs or. js suffix (never save as a txt file, save it in "file type" and select "All Files"), and then turn off this notepad. From the icon of the file has become a script file, double-click to execute the file, see the results (as shown in Figure 1), we edited the first script has been successfully run!
Figure 1
Now, let's take a look at the process of scripting files being executed via WSH. First, WSH queries the required script engine in the system registry based on the script file suffix name, such as VBScript or JScript. Script commands are then executed using the appropriate scripting engine, where some script directives use the WSH built-in objects (such as processing registry entries), at which point the script instruction requests the WSH and completes the instructions by WSH.
So how do you write and run the WSH script? WSH script file is very convenient to write, you can choose any text editor to write, after writing, you simply save it as WSH supported by the file name on the line (such as. js file,. vbs file). The most common editor is the Notepad we used to write the first script file.

First, WSH preliminary
Let's take a look at some of the initial examples of WSH, where each instance can implement a simple function, and after we understand the functionality of each instance, we'll combine these examples into a very practical script that will help you achieve practical, personalized, and powerful functionality.
1. Create shortcuts on the desktop
WshShell = WScript.CreateObject ("Wscript.Shell");
DesktopPath = Wshshell.specialfolders ("Desktop");
SHORTCUT1 = wshshell.createshortcut (DesktopPath + "\ Notepad shortcuts. lnk");
Shortcut1.targetpath = "C:\\windows\\notepad.exe";
Shortcut1.save ();
Where specialfolders This function is used to read the desktop path, after getting the desktop path, create a "\ Notepad shortcuts. lnk" File on the desktop, The target of this shortcut file is directed to Notepad.exe, and finally the information is saved, and the script's work is done.

2. Execute a specific command
The following example opens the "C:\autoexec.bat" file in Notepad and opens the DOS Command window (which results in the execution of the Dir c:\Windows) with the following program code:

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

Open 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 example above, the application opened will remain open, and WSH will continue to execute the following program code. To wait for the application to shut down before proceeding with the following WSH program code, you can add additional parameters after run (). What should we do if we need to continue to execute after we close Notepad?

How to execute other applications by WSH and wait until the application finishes to execute the WSH program code
Shell = new ActiveXObject ("Wscript.Shell");
Intreturn = Shell. Run ("notepad" + wscript.scriptfullname, 1, true);
Shell. Popup ("Notepad has been turned off!") ");

3. List all files in a specific directory
Creating File System objects
FSO = new ActiveXObject ("Scripting.FileSystemObject");
Point to the specified folder
Dir= "C:\\Windows\\Temp";
Fsofolder = fso. GetFolder (dir);
To collect files contained in a folder
Colfiles = Fsofolder. Files;
FC = new Enumerator (colfiles);
Displays and continues to read the file names of other files until you finish
WScript.Echo ("Files under \" "+dir+" \ ":");
for (;!fc.atend (); Fc.movenext ()) {
WScript.Echo (Fc.item ());
}
After the script executes, all file one by one in the specified directory (C:\windows\temp) is listed.

4. Display the native IP address
WS = new ActiveXObject ("Mswinsock.winsock");
WScript.Echo ("Native IP address is:" + ws.) Localip);
The IP address is collected and displayed by Mswinsock.winsock this function.

5. List disk drives and their associated properties

FSO = new ActiveXObject ("Scripting.FileSystemObject");
drivetypenames=["Unknown type", "Removable disk", "Hard Disk", "Network disk drive", "disc", "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 is ready:" + x.isready);
if (X.isready) {
WScript.Echo ("Volume Label:" + X.volumename);
WScript.Echo ("Space size:" + x.availablespace + "byte");
}
}
After executing this script, it will show the type, volume label, space size, share name and other related information of the disk drive.

6. Show Current time
Today = new Date ();
WScript.Echo ("The computer fan tells the clock for you:" +today.tolocalestring ());
In addition to such a method, there is a more complex way to show the time on the afternoon
function GetTime () {
Today = new Date ();
hour = Today.gethours ();
minute = Today.getminutes ();
Second = Today.getseconds ();
Prepand = (hour>=12)? "The Afternoon": "The Morning";
hour = (hour>=12)? Hour-12:hour;
str = "Now time is" +prepand+hour+ "point" +minute+ "minute" +second+ "seconds";
return (str);
}
WScript.Echo (GetTime ());

7. Save the current Web page
Crawl a Web page and save its contents in a file
Inet=new ActiveXObject ("inetctls.inet");
Download the URL
inet. Url= "http://www.pcfans.net/index.htm";
Set timeout
inet. requesttimeout=20;
Download files
WScript.Echo ("Downloading \" "+inet. url+ "\" ... ");
Content = inet. OpenURL ();

Write to 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 ("From" "+inet"). Url+ "" Caught in the content has been deposited, "+filename+" "! ");

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

WScript.Echo ("All of the SYSTEM environment variables list:");
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 seen the system attribute? Do you need to manually view the related configuration for the system environment in the attribute? This script will solve this series of problems.


9. Script to automatically read 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 < i++)
{
mymsg = Objmsg.getnext ();
msg = Mymsg.text;
WScript.Echo (msg);
}
Such a script can automatically find the most recent 10 e-mails from your Outlook Express inbox so that you don't have to open Outlook to read the letters quickly.


10. View the file's detailed properties
var file = "results.html";
Create file system and get files
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 + = "Date Created:" + f.datecreated + "\ n";
FileInfo + = "Last Visit Date:" + f.datelastaccessed + "\ n";
FileInfo + = "Last modified period:" + f.datelastmodified + "\ n";
FileInfo + = "drive:" + f.drive + "\ n";
FileInfo + = "type:" + F.type + "\ n";
Show results
WScript.Echo (FileInfo);

With this function scripting.filesystemobject, we can view the detailed attributes of a file, and if the file you want to view is not in the same directory as the script, you need to enter the full file pathname to view it. No, this script needs to be used in a command-line fashion.
Running in DOS is as follows: Enter "cscript//< script file name >" or "wscript//< script filename >" in DOS row mode window so you can get the effect after the operation.


11. Custom Set Compressed file
WinRAR is one of the more popular compression programs. After the installation completes WinRAR, you first need to add a relative path for WinRAR's run, which is somewhat similar to the path to the executable file in the Config.sys file in DOS. After adding "set Path=c:\windows;c:\program Files\winrar" in the system's environment variable, we can call the WinRAR directly. For winrar command line specific usage, you can enter the RAR.exe/? In a DOS window or a command line window. "You can get help.
After the WinRAR is ready, you can use the following foot to complete the current 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
End If
</script>
Second, comprehensive application
We seem to have so many separate examples, and now we have a little modification of the script above, grouped together, making it a very handy tool that can achieve the following functions:
1. Automatically clears temporary files.
2. Automatically backs up documents, including files in My Documents and messages in Outlook Express.
3. For backed up files, compression is required and the compressed file is named with a date and placed at the specified location.
4. Generate a backup report.
5. Automatic shutdown after completion.
Here is the code that implements the above functionality:
The first step: copy itself to C: and create shortcuts on the desktop
WshShell = WScript.CreateObject ("Wscript.Shell");
Str= "\" "+wscript.scriptfullname+" \ "C:\\shutdown.js"
Wshshell.run ("cmd/c copy" +str,0); Copy this WHS script to C:\shutdown.js
DesktopPath = Wshshell.specialfolders ("Desktop")//Get the actual path to the desktop
SHORTCUT1 = wshshell.createshortcut (DesktopPath + "\ shutdown. lnk"); Start creating shortcuts
Shortcut1.targetpath = "C:\\shutdown.js";
Shortcut1.save ();


Step two: Clear the temporary folder for this user
Envobj = Wshshell.environment ("USER");
Tmp=wshshell.expandenvironmentstrings (Envobj ("TMP")); Get the actual path of the temporary folder for this user
Temp=wshshell.expandenvironmentstrings (Envobj ("TEMP"))//Get the actual path of the temporary folder for this user

FSO = new ActiveXObject ("Scripting.FileSystemObject");
Fso. DeleteFolder (tmp,true); Start deletion (if the temporary folder system is in use, delete failed!) )
Fso. DeleteFolder (temp,true);

Tip: Readers can add other folders that need to be deleted to suit their own reality


Step three://Create a backup folder with a time suffix
var newdate = new Date ();
Bakfolder= "C:\\bak_" +newdate.getyear () + "year" + (Newdate.getmonth () +1) + "month" +newdate.getdate () + "Day _" +newdate.gethours ( + "Time" +newdate.getminutes () + "Min" +newdate.getseconds () + "seconds";
Fso. CreateFolder (Bakfolder);

Tip: Readers can also assign a fixed folder directly to the backup file in a fixed folder.

Step fourth: Start calling WinRAR for backup, directly compress the backed up folder and put the compressed file into the newly built backup folder
First get the folder you want to back up: My Documents and the Outlook Express store folder
Where the Outlook Express Store folder is not the same for each machine, please click the way to obtain:
Open Outlook Express select Tools \ options \ maintenance \ storage folders from the menu
Mydoc= "\" "+wshshell.specialfolders (" mydocuments ") +" ""; Get the actual path to my document
outlook= "\" C:\\Documents and settings\\netbee\\local Settings\\Application data\\identities\\{ 7f935084-e34d-4e22-86e9-10d00355b59d}\\microsoft\\outlook express\ "";
Start compressing the 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: Readers can add other catalogs that need to be backed up to meet their needs. In addition, if the reader modifies the backup directory to a fixed directory in the previous step, you can implement an incremental backup of the backup file with the WinRAR command-line arguments to avoid taking up space on each shutdown backup. Due to space limitations, here is not a list of winrar of the relevant command parameters, please consult the reader winrar help file.
Step Fifth: Create a report in the backup folder that includes the date and time of the backup, the file name after the backup, and the size of the backup file. The report content is displayed at the end.
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 to start shutting down the computer");
Tf. Close ();
Wshshell.run ("notepad.exe" +reportfile, 1, true); Show report Content
Tip: When you generate a report, it appears on the screen and the shutdown operation continues only if the user closes the report. For a direct shutdown, please refer to the second instance of the first part of this article.

Finally, we want this script to be executed automatically when we log off or shut down, as long as the script is specified in Group Policy to log off. The way to do this is to run "gpedit.msc" to open Group Policy, select Local Computer Policy/User Configuration/windows Settings/Scripts-(Logon/Logoff), double-click Logout to open Logoff properties, select Add, select Browse next to script name, find our script and determine, Finally, close Group Policy. Now turn off the machine and try it!
Related Article

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.