Basics of VBScript. VBScript. VBScript Basics WScript Root Class Methods and Properties

Something I completely ran ahead and did not tell you about two dialog box functions: MsgBox and InputBox. In this very short tutorial, I will tell you about all the stray to these two functions. There are also other ways to create dialog boxes, but this will require WSH objects, which will be discussed in the next lessons.

MsgBox Function

The most common function for displaying a message. Of course it is more difficult than Echo of a WScript object, but it doesn't need an object either.
Syntax: MsgBox (Prompt[, Buttons][, Title][, Helpfile, Context])

  • Prompt- Message text.
  • Buttons— Displayed buttons and window mode.
  • Title- Name of the window.
  • Helpfile— help file (*.hlp)
  • Context— Help section number.

Parameter Buttons can take on multiple values ​​at the same time. In order to specify them, use the "+" sign or simply use the sum of the values. The values ​​of this parameter are given below.

Constants for dialog boxes (displayed buttons):

  • vbOKOnly— Value 0. Display OK button.
  • vbOKCancel- Value 1. Display buttons: OK and Cancel.
  • vbAbortRetryIgnore- Value 2. Display buttons: Interrupt, Retry and Skip.
  • vbYesNoCancel- Value 3. Display buttons: Yes, No and Cancel.
  • vbYesNo- Value 4. Display buttons: Yes and No.
  • vbRetryCancel- Value 5. Display buttons: Redo and Cancel.

Constants for dialog boxes (displayed icons):

  • vbCritical- Value 16. Display the Stop Mark icon.
  • vbQuestion- Value 32. Display the Question Mark icon.
  • vbExclamation- Value 48. Display the Exclamation Mark icon.
  • vbInformation- Value 64. Display the Information Mark icon.

Constants for dialog boxes (buttons by default):

  • vbDefaultButton1— Value 0. The first button is selected by default.
  • vbDefaultButton2— Value 256. The second button is selected by default.
  • vbDefaultButton3— Value 512. The third button is selected by default.
  • vbDefaultButton4- Value 768. The fourth button is selected by default.

Constants for Dialog Boxes (Window Mode):

  • vbApplicationModal— Value 0. Displayed in modal mode.
  • vbSystemModal- The value is 4096. It is displayed in modal mode and is located on top of all applications.

Other:

  • Value 262144- Over all windows.
  • Value 524288- The text in the window is displayed on the right edge.

It should be noted that the parameter Buttons cannot take multiple values ​​from the same category. These values ​​will simply add up. That is, you will not be able to install several sets of buttons or icons at the same time.

"VBScript Lesson #16: "Function MsgBox and InputBox "file_1.vbs"************************************** ********************** MsgBox "Hi", 5+16, "Name" MsgBox "Hi", vbRetryCancel+16, "Name" MsgBox "Hi" , vbRetryCancel+524288, "Name" MsgBox "Hi", vbAbortRetryIgnore + vbInformation + vbDefaultButton2 + vbSystemModal + 524288, "Name" MsgBox "Hi", 528706, "Name"

"********************************************************

"VBScript Lesson #16:

"MsgBox and InputBox Function

"file_1.vbs

"********************************************************

MsgBox "Hi" , 5 + 16 , "Name"

MsgBox "Hi" , vbRetryCancel + 16 , "Name"

MsgBox "Hi" , vbRetryCancel + 524288 , "Name"

MsgBox "Hello" , vbAbortRetryIgnore + vbInformation + vbDefaultButton2 + vbSystemModal + 524288 , "Name"

MsgBox "Hi" , 528706 , "Name"

In addition, the MsgBox function can return the result of pressing buttons. You can assign it to a variable and in this way determine the pressed button.

Return result of pressed buttons (constants):

  • vbOK— Value 1. OK button.
  • vbCancel— Value 2. Cancel button.
  • vbAbort— Value 3. Abort button.
  • vbRetry— Value 4. Repeat button.
  • vbIgnore— Value 5. Skip button.
  • vbYes— Value 6. Yes button.
  • vbNo— Value 7. No button.

"******************************************************* ******* "VBScript Lesson #16: "Function MsgBox and InputBox "file_2.vbs"*************************** ******************************* Dim Knopka Knopka = MsgBox("Press any button",2,"Title") If Knopka = 3 Then MsgBox "You pressed a button - Abort" ElseIf Knopka = 4 Then MsgBox "You pressed a button - Repeat" Else MsgBox "You pressed a button - Ignore" End If

"******************************************************* ******* "VBScript Lesson #16: "Function MsgBox and InputBox "file_4.vbs"*************************** ******************************* Dim Dict, AboutBomb Set Dict = CreateObject("Scripting.Dictionary") Dict.CompareMode = 1 Dict .Add "Yellow", "Bomb exploded!" Dict.Add "Red", "You have defused the bomb!" Dict.Add "Blue", "Bomb exploded!" Dict.Add "Green", "Bomb exploded!" AboutBomb = InputBox("Bomb detected!!! Which wire to cut: yellow, red, blue or green??","Bomb detected!!!","Enter wire color here...") If Dict.Exists(AboutBomb) then MsgBox Dict.Item(AboutBomb) else MsgBox "You're visually impaired! There is no such wire! The bomb exploded!!!" end if

"********************************************************

Data types

The VBScript language uses a single data type - Variant (Variant), which allows you to store in variable number, string, date, boolean value, object reference and other information. You can determine the content type of a variable using a set of functions: VarType , TypeName, IsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObject, which will be discussed below. The type of information contained is also called a variant subtype. For a complete list of subtypes, see following table:

Subtype Description
Empty The variable has not been assigned a value. When using an uninitialized variable in numeric expressions, 0 will be substituted, and in string expressions, an empty string.
Null The variable contains no data.
Boolean Boolean variable can take values ​​True or False.
bytes An integer in the range 0 to 255.
Integer An integer in the range -32768 to 32767.
Currency A fixed-point number in the range -922337203685477.5808 to 922337203685477.5807.
Long An integer in the range -2147483648 to 2147483647.
Single A single precision floating point number. For negative values, valid range

from -3.402823E38 to -1.401298E-45. For positive ones - from 1.401298E-45 to 3.402823E38.

Double A double-precision floating-point number. For negative values, the valid range is from

79769313486232E308 to -4.94065645841247E-324. For positive ones, from 4.94065645841247E-324 to 1.79769313486232E308.

Date (Time) Contains a number representing a date between January 1, 100, and December 31, 9999.
String A sequence of characters. The maximum length is around 2 billion characters.
Object An object.
error Error number.

Depending on the expression in which the variable participates, its contents will be automatically cast to the desired type. Consider this example:

Option Explicit Sub TestVBScript Dim A, B A = 5 B = "12" Application.MessageBox A + B, "", vbOkOnly End Sub

Since the expression involves a numeric variable A, the interpreter converts the value of the variable B from string "12" into a number and sum them up:

Let's change the macro so that the variable A also contained the line:

Option Explicit Sub TestVBScript Dim A, B A = "5" B = "12" Application.MessageBox A + B, "", vbOkOnly End Sub

Let's run it for execution. Now the result of the concatenation (concatenation) of two strings will appear on the screen, and not the sum of their numerical representations:

To avoid confusion with automatic type conversion, it is recommended to use the conversion functions: CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr.

If the result of an expression should be exactly the confluence of strings, and not the sum of their numeric representations, then the & operator should be used instead of +.

Variables

A variable is a convenient symbol for a memory location where an application stores some data. During the execution of the application, the value of a variable can change. A variable must be declared with the Dim statement before it can be used.

With the help of one operator, you can declare several variables at once, if you list their names separated by commas:

Left, Right, Top, Bottom

When declaring, there is no need to specify a data type, since all variables are of type Variant.

If Option Explicit is not specified in the first line of the script text, then variables can be used without declaration. But, this way can lead to hard-to-detect errors. It is enough to make a mistake in writing the variable name once in the program text to get an unpredictable result. We recommend that you always specify Option Explicit and declare variables.

The variable name must meet the following requirements:

  1. Start with a Latin alphabet character;
  2. Consist only of Latin alphabet characters or of Latin alphabet characters and numbers;
  3. Do not exceed 255 characters in length;
  4. Be unique within its scope.

Scope and lifetime

The scope of a variable is determined by where it was declared. If inside the body of the procedure, then such a variable is called local and is available only within this procedure. If a variable is declared in the text of a script, then it will be visible to all procedures or functions defined in this script. Local variables can have the same name if they are declared in different procedures.

In the Explorer tree of the Script Object Editor window, there is a special section - Constants and Variables - for declaring global variables visible to all project script functions.

The interpreter allocates memory for local variables at the time they are declared and releases them when the procedure exits. Global variables exist from the moment they are declared until the script finishes its execution. As applied to Gedymin, this means that global variables exist throughout the entire execution of the program.

Assigning a value to a variable

The value of a declared variable is assigned using the = operator. The variable name is specified to the left of the operator, the new value to the right. For example:

A = 200 B = "Name"

Scalar variables and arrays

A variable containing a single value is called a scalar variable. Sometimes, it becomes necessary to store several values ​​in one variable. In this case, you should declare an array. The declaration syntax is identical to the declaration of a scalar variable, except that after the name in parentheses, we specify the size of the array. The following declaration will create an array of 12 elements:

Dim Monthes(11)

In VBScript, the left end of an array index is always 0. Thus, the size of an array is calculated as the number in parentheses plus one. When assigning a value to an array element, you must specify its index in parentheses:

Monthes(0) = "January" Monthes(1) = "February" Monthes(2) = "March" ... Monthes(10) = "November" Monthes(11) = "December"

Similarly, when accessing the value of an element, we use its index:

MonthName = Monthes(5)

The array does not have to be one-dimensional. VBScript allows us to specify up to 60 dimensions when declaring an array. For example, the following statement will create a two-dimensional array with 12 rows and two columns:

DimMonthDays(11, 1)

When accessing elements of a multidimensional array, all indices must be specified:

MonthDays(0, 0) = "January" MonthDays(0, 1) = 31 MonthDays(1, 0) = "February" MonthDays(1, 1) = 28 ...

Above, we declared arrays, the size of which does not change during the course of the program. If it is not known in advance how many elements will be needed, then you can declare a dynamic array:

Before use, you should set the size of a dynamic array using the ReDim operator:

ReDim A(25)

During execution, you can call the ReDim statement multiple times, each time changing the size of the array. The Preserve option preserves the values ​​of the array elements when resizing. For example, the following code will increase the array declared above by five elements, leaving the existing ones intact:

ReDim Preserve A(30)

Remember that when the array size is reduced, the values ​​of the removed elements will be irretrievably lost. With the Erase operator, you can clear the elements of a fixed array or free the memory occupied by a dynamic array.

Dim A ReDim A(25) ... Erase A

Constants

It is a good practice to declare constants for values ​​that are used repeatedly in the program text. A well-named constant improves readability, and the use itself makes it easier to make changes to the code. Unlike variables, the value of a constant cannot be changed during program execution. A constant is created using the Const operator:

Const CountryName = "Belarus" Const CountryCode = 375

Several constants can be declared within one statement, separated by commas. Like a variable, a constant has its own scope, depending on where (in a procedure or outside it) and how (Public or Private) it was declared. Constants created by the Const statement without specifying Public or Private are public by default.

In the Explorer tree of the Script Object Editor window, there is a special section - Constants and Variables - for declaring global constants visible to all project script functions.

String constant values ​​are enclosed in double quotes.

Values ​​of the Date type should be framed with hash marks (#) and use the US format: month/day/year. For example:

Const Public IndependenceDay = #03/25/1918#

To avoid confusion between constants and variables, it is recommended to use a single prefix for all constants, such as "con", or to type the name of the constant in uppercase.

To make the programmer's job easier, VBScript contains a set of predefined constants.

Operators

VBScript operators fall into five categories: arithmetic, comparison, merge, boolean, and assignment.

Arithmetic operators

Operator Usage example Description
^ number ^ exponent Raises number to the exponent power. Number can only be less than zero if it is an integer power. If one of the operands is Null, the entire expression evaluates to Null. If multiple exponentiations are performed in a row, the result is calculated from left to right.
* number1 * number2 The product of two numbers. If the operand is Empty, then it is assumed to be zero. If at least one of the operands is Null, the entire expression evaluates to Null.
/ number1 / number2 Real division of two numbers. Operands are governed by the same rules as the multiplication operator.
\ number1\number2 Integer division. Both operands are cast to Byte, Integer, or Long before evaluation. Otherwise, the same rules apply as for the division operator.
Mod number1 Mod number2 The remainder of an integer division. Casting operands to an integer, as well as the rules for handling Empty and Null, as in integer division.
+ expression1 + expression2 If both operands are numbers, the result is their arithmetic sum. If both operands are strings - merge (concatenation) of two strings. If one operand is a number and the other is a string, then the string operand will be converted to a number and added to the numeric. If at least one of the operands is Null, the entire expression evaluates to Null. If both operands are Empty, the result is an integer value of 0. If only one operator is Empty, the value of the second operand is returned as the result.
- number1 - number2 or - number In the first case, it returns the difference of two numbers. In the second, it inverts the sign of the number. Rules for operands with Null and Empty values, as for the multiplication operator.

Comparison Operators

The format for using comparison operators is:

Result = expression1 comparisonoperator expression2

where the following comparison operators are used:< (меньше), <= (меньше или равно), >(greater than), >= (greater than or equal to), = (equal to),<>(not equal).

Depending on the types and values ​​of the operands, the comparison is carried out as follows:

If That
Both operands are numbers. The two numbers are compared.
Both operands are strings. The two strings are compared.
One of the operands is a number and the second is a string. The string operand is cast to a number and the two numbers are compared.
One of the operands is Empty, and the second is a number. An operand with the value Empty is assumed to be 0.
One of the operands is Empty, and the second is a string. The operand with the value Empty is taken equal to the empty string "". The two strings are compared.
Both operands are Empty. The operands are considered equal.
At least one of the operands is Null. The result is Null.

The special Is operator is used to compare two object variables and returns True if both variables refer to the same object instance.

Concatenation Operators

Result = expression1 & expression2

If the operand is not a string, it is cast to a string type. If both operands are Null, then the result is also Null, however, unlike the other operators, if only one operand is Null, then it is taken equal to the empty string. An operand that has the value Empty is also treated as the empty string "".

Logical operators

VBScript provides us with the following logical operators:

  1. Boolean exception (Xor);
  2. Logical equivalent (Eqv);
  3. Logical implication (Imp).

Boolean expressions or numeric values ​​can act as operands of logical operators. In the first case, the result will be a boolean constant, in the second, a number. Depending on the operator, giving one or two Null values ​​as input may result in a Null result. The Not operator is unary and returns the logical negation of the expression. On a numeric operand, the Not operator performs a bitwise inversion. The rest of the logical operators are binary. The table below shows the results of executing each of the operators depending on the value of the operands Exp1 and Exp2:

Exp1 Exp2 And Or Xor Equv imp
True True True True False True True
True False False True True False False
False True False True True False True
False False False False False True True
True Null Null True Null Null Null
False Null False Null Null Null True
Null True Null True Null Null True
Null False False Null Null Null Null
Null Null Null Null Null Null Null

In real life, And and Or operators are most often used, and Xor is much less common. We have not encountered the use of the Eqv and Imp operators in practice. If you find it difficult to understand the above table, we summarize the action of these operators:

  • And is True only if both operands are True. In any other case, it is either False or Null.
  • Or evaluates to True if at least one of its operands is True.
  • Xor is True if the operands are different and False if they are the same.

When executed bitwise on numeric operands, the result of a logical operator is determined by the following table:

Exp1 Exp2 And Or Xor Equv imp
0 0 0 0 0 1 1
0 1 0 1 1 0 1
1 0 0 1 1 0 0
1 1 1 1 0 1 1

assignment operator

The assignment operator (=) is described in detail in the "Variables" section.

Order of Application of Operators

If an expression contains multiple operators, they are applied according to a set order called operator precedence. You can change the default order using parentheses. The expression inside the parentheses is always evaluated first.

In an expression containing operators of different categories, the arithmetic operations are performed first, then the comparison operators, and finally the logical operators. All comparison operators have the same precedence and are evaluated from left to right. Arithmetic and logical operators are evaluated in the following order:

  1. Exponentiation (^);
  2. Number change sign, unary minus (-);
  3. Multiplication (*) and division (/);
  4. Integer division (\);
  5. Remainder of integer division (Mod);
  6. Addition (+) and subtraction (-);
  7. String concatenation (&).

If multiplication and division occur in the same expression, then the operations are performed in left-to-right order. A similar rule applies in the case of the simultaneous presence of addition and subtraction operators.

The string concatenation operator (&) is not arithmetic and takes precedence between arithmetic and comparison operators.

The order for logical operators is as follows:

  1. Logical negation, inversion (Not);
  2. Logical multiplication, conjunction (And);
  3. Logical addition, disjunction (Or);
  4. Boolean exception (Xor);
  5. Logical equivalent (Eqv);
  6. Logical implication (Imp).

Conditional expressions

Conditional expressions are used to control the order of execution of program commands and allow you to organize transitions (branching) and repetition of commands. Typically, comparison operators are used in conjunction with conditional expressions.

If..Then..Else expression

The conditional jump expression If allows you to execute one or another group of commands depending on the result of a logical expression or the value of a Boolean variable.

To execute a single command when a given condition is met, use the single-line expression syntax:

Dim S If DatePart("w", Now) = vbMonday Then S = "Monday" Application.MessageBox S, "", vbOkOnly

Note that the Else section is omitted in this case. To execute a group of statements, enclose them between the Then and End If keywords.

Dim S If DatePart("w", Now) = vbMonday Then S = "Today is Monday" Application.MessageBox S, "", vbOkOnly End If

If one code is required when the condition is met, and another code is required when the condition is not met, then the syntax of the expression with the Else section is used:

Dim S If DatePart("w", Now) = vbMonday Then S = "Today is Monday" Else S = "Today is not Monday" End If Application.MessageBox S, "", vbOkOnly

If you need to choose from several alternatives, the syntax with the ElseIf construct is suitable:

Dim S, D D = DatePart("w", Now) If D = vbMonday Then S = "Monday" ElseIf D = vbTuesday Then S = "Tuesday" ElseIf D = vbWednesday Then S = "Wednesday" ... End If Application. MessageBox S, "", vbOkOnly

If expressions can be nested:

Dim S, D D = DatePart("w", Now) If D = vbMonday Then S = "Monday" Else If D = vbTuesday Then S = "Tuesday" Else If D = vbWednesday Then S = "Wednesday" Else ... End If End If End If

While there is no limit to the number of ElseIf sections in a conditional expression, extensive use of them can lead to confusing, unreadable code. In the case of choosing one alternative out of many possible, depending on the value of some selector, it is recommended to use the Select Case expression.

Select..Case expression

Let's rewrite the example with days of the week using a select expression:

Dim S Select Case DatePart("w", Now) Case vbMonday S = "Monday" Case vbTuesday S = "Tuesday" Case vbWednesday S = "Wednesday" ... Case Else Err.Raise 32000, "", "Unknown day of the week End Select

Since the selector expression is evaluated only once, using Select..Case results in more efficient code. It is recommended that you always use the Case Else section to catch invalid or raw selector values.

Loop statements

Quite often there is a situation when the code needs to be re-run. To do this, write a loop statement that repeats certain commands over and over again. Loop statements are used in many situations: when calculating a grand total over a list of numbers, moving through the records of a dataset, or running a block of code on multiple objects. There are several cycles described in the following sections. Some of them are executed while the condition is True, some of them are False. And, finally, there are those that are executed a given number of times.

Do..Loop statement

This statement is intended to execute a group of commands until the specified condition is True or until it becomes True. The condition check can be carried out as at the beginning of the loop:

Do [(While | Until) condition] Loop

so at the end:

Do Loop [(While | Until) condition]

The Exit Do command can occur an unlimited number of times in the loop body. It is usually used in conjunction with the If..Then conditional statement and allows control to be transferred to the statement immediately following the loop. When using Exit Do inside a nested loop, control will jump to the outer loop.

The following code allows you to replace the dice:

Dim Resp, Num Do Num = Int(6 * Rnd + 1) Resp = Application.MessageBox(Num & " Another number?", "",_ vbYesNo or vbQuestion) Loop Until Resp = vbNo

While..Wend

It is a truncated version of the Do..Loop operator and allows you to execute a group of commands while the condition is True. Operator syntax:

While condition Wend

Note that Exit Do has no effect inside this loop. While..Wend loops can be nested.

For..Next

This loop repeats a given set of commands a specified number of times. The operator syntax is:

For counter = start To end Next

Before the loop starts, the variable counter is assigned the value start. Next, the condition counter is checked<= end, при step >= 0, or counter >= end, with a negative step. After executing the command block, the counter variable is incremented by the step value and everything repeats from the beginning.

Changing the counter in the loop body is not prohibited, but it is strongly discouraged, as it makes it difficult to understand the program logic and debug it.

Exit For can occur any number of times in the loop body. Loops can be nested. For example, this loop initializes a three-dimensional array:

Dim A(9, 9, 9) Dim I, J, K For I = 0 To 9 For J = 0 To 9 For K = 0 To 9 A(I, J, K) = 1 Next Next Next

For Each..Next

The For Each..Next loop statement repeats a given set of commands for each element of an array or collection and has the following syntax:

For Each element In group Next

The loop is executed if there is at least one element in the array or collection. Exit For can occur any number of times in the loop body.

Illustrate using For Each..Next using the following code as an example, which displays a list of files from the root directory of the drive c:\

Dim fso, f, f1, fc, s Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFolder("c:\") Set fc = f.Files For Each f1 in fc s = s & f1 .name & vbNewLine Next Application.MessageBox s, "Files on c:\", vbOkOnly

Procedures

To save memory and structure the program, a code fragment that is called repeatedly in different places can be formatted as a procedure. There are two types of procedures in VBScript: subroutines (Sub) and functions (Function). A subroutine is a sequence of statements surrounded by the keywords Sub and End Sub. A subroutine can take parameters as input, but does not return a value. A function - a sequence of statements between Function and End Function -- returns a result and can therefore be used in an expression. Each procedure must have a name that is unique within the module. The names of procedures declared in a global module must be unique throughout the project.

The definition of a subroutine and a function has the following syntax:

| Private] Sub name [(arglist)] End Sub | Private] Function name [(arglist)] End Function

Public procedures are global and available in all program scripts. Private procedures are only available in the script where they are declared. Unless otherwise noted, a declared procedure is public. The Default keyword can only be used in the body of a class and is used to specify the default method of that class.

The parameter list has the following syntax:

Varname[, ...]

Parameters can be passed by value (ByVal) or by reference (ByRef). By default, all parameters are passed by value. Constants, expression evaluation results can only be passed by value. Changing a parameter passed by reference will change the value of the external variable. Let us explain the passing of parameters into a procedure using the following example:

Sub DoCalculation(ByRef A, ByVal B, ByVal C) A = C * 2 B = C / 2 End Sub Sub TestVar Dim V1, V2 V1 = 1 V2 = 2 DoCalculation V1, V2, 10 20" V2 = 2 End Sub

Variables declared inside the body of a procedure are local and are destroyed when the procedure ends. The values ​​of local variables are not saved.

The parameter list is specified in parentheses when a function is called or when a subroutine is called using the Call statement. So, we could write the call to the DoCalculation procedure in the example above as follows:

Call DoCalculation(V1, V2, 10)

Execute expression

VBScript classes

VBScript allows you to create new classes, which we will refer to as VB classes from now on. Generally speaking, they are not full-fledged classes in the understanding of object-oriented programming, since they do not support inheritance and, accordingly, polymorphism. So, of the three pillars on which the object-oriented paradigm is based, only encapsulation remains - the ability to combine data and methods within one entity.

The class is defined using the following construct:

Class name statements End Class

where name is the name of the class, and statements are one or more definitions of variables, properties, procedures, or functions, also called class members. Please note that unlike Delphi, where the class definition code contains only declarations of procedures and functions, in the VB class, the member code is written directly in the class text.

Class members can be declared as Private or Public. The first ones are visible only inside the code of this class, while the second ones are available both for the internal code and outside. If a variable or function (procedure) does not contain an explicit definition of Public or Private, then they are considered public. Procedures or functions declared as Public inside a class block become methods of that class.

Variables declared as public become class properties along with properties declared directly using the Property Get, Property Let, Property Set constructs.

Defining class properties

Above, we have already said that the fields of a class, explicitly or implicitly declared as Public, become its properties. In addition, you can create a class property by defining special functions for reading the value of the property (Property Get), as well as for assigning it (Property Let or Property Set).

The syntax for defining such functions is as follows:

| Private] Property Get name [(arglist)] [ name = expression] [ name = expression] End Property Property Let name ( value) End Property Property Set name( reference) End Property

By defining only one function, read or set, you can create a property, respectively, read-only or write-only. The Property Let procedure is used to assign simple data types, and the Property Set procedure is used to pass a reference to an object. Note that all three functions can accept an arbitrary list of parameters as input. In this way, you can organize, for example, array properties, passing the element index as an argument.

Creating and Destroying an Instance of a VB Class

Creating an instance of a VB class is done using the New operator.

Dim X Set X = New classname

The destruction of the previously created instance occurs automatically upon completion of the block of code where the corresponding variable was declared and provided that there are no external references to it. If you need to destroy the instance manually, you must assign the Nothing value to the variable.

‘ Declaring a variable and creating a class instance Dim X Set X = New classname ... ‘ Using a class instance ... ‘ Destroying a class instance Set X = Notning ...

Initialize and Terminate events

The Initialize event occurs when an instance of a class is created, and the Terminate event occurs when it is destroyed. The developer can define his own event handlers. The following is an example of using object creation and deletion events:

Class TestClass " Define an Initialize event handler. Private Sub Class_Initialize MsgBox("TestClass started") End Sub " Define a Terminate event handler. Private Sub Class_Terminate MsgBox("TestClass terminated") End Sub End Class " Create an instance of the TestClass class. " The message "TestClass started" will be displayed. Set X = New TestClass " The instance is destroyed. " The message "TestClass terminated" will be displayed. Set X = Nothing

Continuation

Visual Basic Script

Why VBS scripts are needed

VBS script is a powerful solution for automating user actions in Windows family systems. This type of script is commonly used for:

  • creating complex scenarios;
  • using objects from other applications and libraries;
  • hiding windows during script execution;
  • script logic encryption.

Basically, VBS scripts are used for data processing, system management, work with user and computer accounts, interaction with office applications, work with databases, and other complex tasks.

Key points

Depending on the script language, content and encryption, there are the following types of scripts:

  • vbs - Visual Basic Script
  • vbe - encrypted Visual Basic Script
  • js - JavaScript
  • jse - encrypted Java Script
  • wsh - script settings
  • wsf - XML ​​Integrated Script

In this article, I will be looking at scenarios like vbs.

Scripts are usually edited in Windows Notepad, but I recommend using Notepad2, which highlights Visual Basic language keywords and helps format the body of the script. So, a vbs script is a plain text file named *.VBS, which is easy to edit in notepad, and run for execution by double-clicking or calling by name in the console.

As described above, scripts are not compiled, but interpreted. That is, to process the script, the system must have a VBS language interpreter, and there are even two such interpreters in Windows: windowed WScript and console CScript - both interpreters are Windows script host(WSH).

By default, all scripts are executed through WScript, so no settings are required, but to execute a script in a console window, you must run it through CScript, or set CScript as the default interpreter. To do this, run the following on the command line:

CScript //H:CScript

After that, all scripts will be executed in console mode. Returning to windowed mode is done with the following command:

CScript //H:WScript

The following rules work in Visual Basic:

  • string length is not limited;
  • characters are case insensitive;
  • the number of spaces between parameters is not taken into account;
  • the command line can be broken, and at the break point you need to insert the symbol "_";
  • the maximum length of a variable name is 255 characters;
  • comments are marked with " " ".

" === Script Information Header === " Script Name: " script name; " Date: " modification date; " Author: " author; " Description: " description; " === Initialization Block === Option Explicit " directive , which prevents automatic creation of " variables; Dim " variable declaration; Dim () "declaration of arrays; Set " object connection; " === Script Main Logic === " script body; " === Functions and Procedures === " procedures and functions;

Variables

By default, variables in scripts are declared automatically the first time they are used in the script body, unless this is prohibited by the Option Explicit directive. If, however, the Option Explicit directive is declared at the beginning of the script, then all variables must be defined in advance using the following constructs:

Dim " variable available to all subroutines; Public " variable available to all subroutines; Private " a variable accessible only to the current program and its subroutines;

Constants are declared at the beginning of the script with the construct:

Const = " constant available to all subroutines; Public Const = " constant available to all subroutines; Private Const = " constant available only to the current program " and its subroutines.

The variable type is assigned automatically after the first value is entered into it. The following data types exist in Visual Basic:

  • empty - uninitialized variable;
  • null - empty variable;
  • boolean - boolean type, possible values: False, True or 0, 1;
  • byte - 8-bit unsigned integer, possible values: 0 .. 255;
  • integer - 32-bit integer, possible values: -32768 .. 32767;
  • long - 64-bit integer, possible values: -2147483648 .. 2147483647;
  • currency - money type, possible values: -922337203685477.5808 to 922337203685477.5807;
  • single - floating point number, possible values: -3.402823e38 .. -1.401298e-45 for negative numbers and 1.401298e-45 .. 3.402823e38 for positive numbers;
  • double - floating point number, possible values: 1.79769313486232e308 .. -4.94065645841247e-324 for negative numbers and 4.94065645841247e-324 .. 1.79769313486232e308 for positive numbers;
  • date - date, possible values: 01/01/1900 and 01/31/9999;
  • string - string variable, capacity up to 2 billion characters;
  • object - a pointer to an object;
  • error - error code.

Data can be checked for conformance to types, as well as transferred from one type to another, if the values ​​allow it. The following commands are used for operations on data types:

VarType( ) " return the type number of the variable; TypeName( ) " return variable type name; IsArray( ) " checking that the variable is an array; IsDate( ) " checking that the variable is a date; IsEmpty( ) " checking that the variable is uninitialized; IsNull( ) " checking that the variable is empty; IsNumeric( ) " checking that the variable is a number; IsObject( ) " checking that the variable is an object; CCur( ) " conversion to currency type; CBool( ) " convert variable to boolean type; CByte( ) " convert variable to byte type; CDate( ) " convert variable to date type; CDbl( ) " converting a variable to double type; CInt( ) " convert variable to integer type; CLng( ) " convert variable to type long; CSng( ) " convert variable to type single; CStr( ) " converting a variable to a string type.

As mentioned above, Visual Basic does not impose strict restrictions on variable names, but at the same time, there are recommendations for variable names so that it is easy to determine the data type in the script text. To do this, it is recommended to put conditional symbols before the variable name, which determine the type of the variable:

  • iValueName - numeric types
  • sValueName - string type
  • bValueName - boolean type
  • dValueName - date
  • oValueName - object
  • cValueName - constant
  • aArrayName - an array

VBS scripts can use arrays of variables, which allow you to store lists, tables, and even more complex structures. One-dimensional arrays (lists) can be dynamic, that is, they allow you to change their dimension during the script. All arrays are declared with the Dim command:

Dim

An example of using arrays

Dim aMyArray1(10,10) "Creating a 11x11 static array; Dim aMyArray2() "Creating a dynamic array; aMyArray1(0,0) = "Hello" " array filling; aMyArray1(0,1) = "People" " array filling; aMyArray1(1,0) = "World" " array filling.

Before using a dynamic array, it needs to specify the current dimension using the ReDim command, after which the array can be reshaped anywhere in the script, either clearing the entire array or preserving the old cell values ​​with the Preserve command:

ReDim aMyArray2(0) " forming an array of one element; aMyArray2(0) = "Hello" " filling the array; ReDim aMyArray2(1) " deleting the old array and forming a new one from " other elements; aMyArray2(0) = "Hello" " array filling; aMyArray2(1) = "World" " array filling; ReDim Preserve aMyArray2(2) " forming an array of three elements, leaving " the old values ​​of the elements in the cells where they were; aMyArray2(1) = "!" " filling the array; Erase aMyArray2 " deleting the array.

To find out the dimension of an array, one usually uses the UBound function, which will be discussed below along with other data manipulation functions.

Branching by condition

Not a single full-fledged scenario is complete without branches, branches help you choose the right path when a certain condition is met or not met. In other words, branches implement the script's logic. VBS scripts implement several branching mechanisms. Let's consider them in order.

Construction for one action performed by condition:

If Then

Construction for several actions performed by condition:

If Then end if

Fork design:

If Then Else end if

Construction "fork into several paths" (option cIf):

If Then ElseIf Then Else end if

In all the above constructions, the following rule applies: "If the condition , then produce a list of actions , which are located under the current condition block. If the current condition is not met, then go to the list of actions under Else."

Construction "fork into several paths" (variant with Select):

Select Case case case Case Else End Select

In this construction, the rule works: "If the value of the variable equals value , then produce a list of actions under this value, otherwise go to the next value check ."

Cycles

Loops are usually used to organize repetitive actions or iterate over array elements. Several types of loops are organized in VBS scripts: a regular loop, a loop with an unknown number of iterations, a loop by condition.

A regular loop is organized by the For - Next structure, the arguments of which specify such parameters as the name of the counter ( ), the initial value of the counter ( ), the end value of the counter ( ) and, if necessary, the counter step (Step ).

For = To Next

If during the loop operation it is necessary to stop enumeration of values, then this can be done using the Exit For command.

For = To If Then Exit For Next

A loop with an unknown number of iterations is usually used to iterate over all the values ​​in a collection of an object when its dimension is not known. This structure will iterate over all values ​​( ) of the array passed as a loop parameter ( ).

For Each In Next

For Each oCurrentFile In oFiles WScript.Echo oCurrentFile.Name Next

Conditional loops are used to process data when a certain condition is met. Such cycles are of two types: with a check at the beginning of the cycle and with a check at the end.

Loop while a condition is true, with a check at the beginning

Do While loop

Loop until condition is met, with a check at the beginning

Do Until loop

As mentioned above, conditions can be placed at the end of the loop. In this case, the body of the loop will be executed at least once. Just like in regular loops, a loop with a condition can be interrupted with the Exit Do command:

Do If Then Exit Do Loop Until

Built-in Functions

To work with data and build their own procedures and functions, Visual Basic developers have already taken care of the basis of scripts - basic functions. VBS scripts functions for working with dates, strings and numbers, as well as basic I / O procedures and network procedures. Let's take a quick look at built-in functions.

Date processing functions:

Date " return the current date; Time " return the current time; Now " return the current date and time; DateDiff( , , ) " return the difference between dates; MonthName( ) " return the name of the month; WeekDayName( , , ) " return the name of the day of the week; Day( ) " return the day from the specified date; Month( ) " return the month from the specified date; Year( ) " return the year from the given date; Hour( ) " return the hour from the specified date; Minute( ) " return the minute from the specified date; Second( ) " return the second from the specified date.

String processing functions:

Asc( ) " return the ANSI code of the character; Chr( ) " return character by ANSI code; InStr( , ) " return the position of the substring in the specified " string; InStrRev( , ) " return the position of the substring in the specified " string, starting from the end of the string; Join( , ) " array to string conversion; Len( ) " return string length; LCase( ) " converting a string to a string of small " characters; UCase( ) " converting a string to a string of large " characters; Left( , ) " return the specified number of characters from the " beginning of the string; Right( , ) " return the specified number of characters from the " end of the string; Mid( , , ) " return the specified number of characters from " the specified character number of the string; Replace( , , [, Params]) " substring replacement in the specified string; Space( ) " strings of the specified number of spaces; Split( , [, Params]) " convert string to array; String( , ) " a string of the specified number " of certain characters; SrtReverse( ) "mirror string; Trim( ) " trim spaces to the left and right of the string; LTrim( ) " trim spaces to the left of the string; RTrim( ) " trim spaces to the right of the string.

Math functions:

Randomize " initialization of the random number mechanism (returns nothing); Rnd " return a random non-integer value from 0 to 1; Atn( ) " calculation of the arc tangent of a number; Cos( ) " calculation of the cosine of a number; Sin( ) " calculation of the sine of a number; Exp( ) " calculation of the natural logarithm of a number; Log( ) "calculation of the decimal logarithm of a number; Sqr( ) " calculation of the square root of a number; Abs( ) " calculation of the absolute value of a number; Hex( ) " calculation of the hexadecimal value of a number; Int( ) " Round number; Fix( ) " calculation of the integer part of the number.

And, of course, in addition to the mentioned functions, scripts support all the simplest mathematical and logical operations:

  • = - assignment operator;
  • + - sum of two numbers;
  • - - subtraction of two numbers;
  • * - multiplication of two numbers;
  • / - division of two numbers;
  • \ - integer division of two numbers;
  • Mod - the remainder of the division of two numbers;
  • ^ - exponentiation;
  • & - concatenation of two strings;
  • Is - comparison of two objects;
  • Eqv - comparison of two expressions;
  • Not - logical negation operation;
  • And - logical operation of conjunction;
  • Or - logical operation of disjunction;
  • Xor - logical operation of elimination;
  • Imp - logical implication operation.

The order in which operations are performed is determined as in all programming languages: first, operations in brackets are performed, then functions are calculated, then multiplication and division operations, followed by addition and subtraction, and the logical operations complete the calculation.

Custom Functions

Scripts written in Visual Basic allow you to define custom procedures and functions and call them from the main program. There is practically no difference between a procedure and a function, the difference lies in the logical sense of these subroutines: functions are usually used to calculate some value, and procedures are used to perform actions. However, both procedures and functions can perform operations and pass values ​​to the main program. Despite this, one should not forget about the purpose of these subroutines: functions - for calculations, procedures - for actions.

The function is declared by the Function operator, followed by the name of the user-defined function, which should not match any reserved word of the Visual Basic language, then the variables that will be passed to the subroutine as parameters - specifying variables in this construction means allocating memory cells for the variables of the subroutine (declaration variables for the function). In the body of a subroutine, the script structure is no different from regular program(here you can declare additional variables, perform operations, use other functions and procedures), at the end of the body there must be an operator for assigning a function to some value - this value will be returned to the main program. You can interrupt the execution of a function with the Exit Function statement, but in this case, you must remember to assign a value to the function, otherwise the script will generate an error. The function ends with the End Function statement.

Function definition

function () If Then = Exit Function End If = end function

Function call

= ()

A procedure is defined similarly to a function, but with a different -Sub operator. Since the procedure does not return any values ​​to the main program, there is no assignment statement before exiting the procedure. You can interrupt the execution of the procedure using the Exit Sub command, and the entire construction is completed with the End Sub statement. To call a procedure in the main program, you must use the keyword Call and the name of the function with the necessary arguments. (The Call keyword is optional, but I recommend using it to avoid incorrect procedure calls.)

Procedure definition

Sub () If Then Exit Sub End If end sub

Procedure call

()

By the way, procedures and functions should be located at the end of the script.

During the operation of the subroutine, the values ​​of the variables of the main part of the script do not change, even if the subroutine contains variables of the same name. In order for the subroutine to be able to change the values ​​of the variables of the main script, it is necessary to set the variable property as ByRef in the arguments of the subroutine. By default, all variables are defined with the ByVal property.

Sub (ByRef [, arguments]) = end sub

In this case, the argument passed by reference to a memory cell - the value of the variable changes in the main script. In other words, using the ByRef parameter, the procedure turns into a function - the subroutine returns the result of the calculation to the main program.

Handling Script Execution Errors

By default, all errors are handled automatically by the script, and if an error occurs, the script stops. To disable automatic error handling, use the special On Error Resume Next directive, which disables automatic error handling and continues the script even if there are errors. For manual error handling, you need to refer to the built-in Err object, which stores the status of errors. The Err object has the following properties and methods:

Number " return the number of the last error; Description " return the description of the last error; Clear " to clear the Err object; Raise " to raise a test error.

An example of manual error handling:

On Error Resume Next iTotalPoints = InputBox("Enter total points") iNumberOfTests = InputBox("Enter number of tests") iAvarage = iTotalPoints / iNumberOfTests Select Case Err.Number Case 0 " no errors; WScript.Echo "Average = " & CStr(iAvarage) Case 11 " division by zero; WScript.Echo "Number of tests cannot be zero" Case 13 "type mismatch; WScript.Echo "You entered a non-numeric value" Case Else " no error; WScript.Echo "Unknown error WScript.Quit" End Select

Objects, their methods and properties

VBS scripts, like their parent language Visual Basic, is an object-oriented programming language, that is, the main concept is the concept of objects and classes

A class is a type that describes the arrangement of objects. An object means something that has a certain behavior and representation, an object is an instance of a class. A class can be compared to a blueprint according to which objects are created. Typically, classes are designed in such a way that their objects correspond to the objects of the domain.

So, in order to work with an object, you must first create it using classes from the required library:

set = CreateObject( .)

You can delete an object by setting it to Nothing:

set = Nothing

All objects that Windows Script Host works with have methods and properties. To access a method, you need to specify an object, and through a dot - a method with the necessary parameters.

. [, Param2, ..., ParamN] Call .([, Param2, ..., ParamN])

The situation is similar with properties, but properties can be both assigned and read into variables and other properties, however, the data type of variables and properties should be taken into account, otherwise the script will generate an error of data type incompatibility.

. = . = . = .

Example. Creating a file system object, calling the create folder method, deleting the object.

Set oFSO = CreateObject("Scripting.FileSystemObject") Call oFSO.CreateFolder("C:\Test") Set oFSO = Nothing

Note that "object" refers to script logic, not file system logic. That is, when we say "object deletion", we mean the logical object of the script, which does not affect the deletion of any parts of the file system.

To find out what libraries exist in your operating system, the classes included in the libraries, their methods and properties, you can use the object explorer, for example from Microsoft Word:

  1. Launch MS Word.
  2. In the main menu, select Tools -> Macro -> Visual Bacis Editor
  3. In the macro editing window select View -> Object Browser

If some library is not reflected in the list, then it can be connected via the Tools -> References menu.

Scripts have methods that are not part of any class, they are available directly in the body of the script:

MsgBox( [, Params]) " display window message on the screen; InputBox( [, Params]) " displays the dialog box.

An example of displaying a dialog box asking for text, and then displaying a window message with the entered text.

MyValue = InputBox("Enter text", "First window", "Text must be entered here") MyResult = MsgBox(MyValue, 1, "Second window")

WScript Root Class Methods and Properties

The methods and properties of the WScript root class do not require the creation of an object - they are automatically available for use directly in the body of the script.

CreateObject( .) " object creation; GetObject( ) " connecting an object from a file; ConnectObject( , ) " connecting to the events of an existing object; DisconnectObject( ) "disconnecting from object events; Echo() " displaying a message on the screen; Arguments " return an array of arguments command line scenario; Name " return the name of the script interpreter; Path " return the path to the script interpreter; FullName " return the full name of the scripting interpreter; Version " return the version of the scripting interpreter; BuildVersion " return the build version of the scripting interpreter; ScriptName " return the name of the script file; ScriptFullName " return the full file name of the script; Interactive " set or return the interactive mode of the script; Sleep( ) " pause for the specified number of milliseconds; Quit " terminate the script.

We will discuss the use of these methods and properties in more detail in examples of other classes.

Shell class methods and properties

To work with the operating system, a special Shell class is used, which allows you to perform such operations as launching programs, changing the registry, creating shortcuts, accessing system folders and system variables, and accessing the system log. So, the methods and properties of the Shell class:

ExpandEnvironmentStrings( ) " return the value of the requested system variable; EnviEnvironment( ) " return an array of system variables; CreateShortcut( ) " creating shortcut; Popup( [, Params]) " display window message on the screen; RegRead( ) "read value from registry; RegWrite( ,[, Type]) "write value to registry; RegDelete( ) " deleting a value from the registry; LogEvent( ,) " log event to system log; Run( [, Params]) " run the program in a new process; Exec( ) "launching the program in the child console; AppActivate( ) "window activation; SendKeys( <Keys>) " send characters to the active window; CurrentDirectory " set or return the current directory; SpecialFolders() " returns an array of service folders or the path " of the requested service folder.</p><p>Example. Using methods and properties of the Shell class.</p><p>" Create an object of the Shell class Set oShell = Wscript.CreateObject("WScript.Shell") " Run the calculator oShell.Run("Calc.exe") " Delay WScript.Sleep(100) " Run the notepad oShell.Run("Notepad.exe ") " Delay WScript.Sleep(100) " Switch to the calculator window oShell.AppActivate "Calculator" " Delay WScript.Sleep(100) " Simulate a keystroke oShell.SendKeys("1(+)2(=)") " Receive path to desktop sDesktopPath = oShell.SpecialFolders("Desktop") " Create shortcut object Set oLink = oShell.CreateShortcut(sDesktopPath & "\Test.lnk") " Set shortcut oLink.TargetPath = WScript.ScriptFullName oLink.WindowStyle = 1 oLink .Hotkey = "CTRL+SHIFT+T" oLink.IconLocation = "notepad.exe,0" oLink.Description = "Test link" oLink.WorkingDirectory = sDesktopPath oLink.Save " Create an environment object and get system properties into it Set oSysEnv = oShell.Environment("SYSTEM") " Displaying a message about the number of processors on the screen MyResult = oShell.Popup("Number of processors: " & oSysEnv("NUMBER_OF_PROCESSORS"), _ 3, "Message", 0) " Getting the path to <a href="https://unitarmy.ru/en/windows-8/kak-postavit-parol-na-papku-v-windows-7-bez-programm-kak.html">Windows folder</a> and outputting a message to the screen MyResult = oShell.Popup("Windows directory: " & _ oShell.ExpandEnvironmentStrings("%WINDIR%"), 3, "Message", 0) " Reading the registry key and displaying its value on the screen WScript.Echo oShell.RegRead("HKLM\Software\Microsoft\Windows\CurrentVersion\ProductID") " Write a string value to the registry MyResult = oShell.RegWrite("HKCU\ScriptEngine\Value", "My Value") " Write a numeric value to the registry MyResult = oShell.RegWrite("HKCU\ScriptEngine\Key", 1, "REG_DWORD") " Deleting a registry key MyResult = oShell.RegDelete("HKCU\ScriptEngine\") " Writing an event to the system log MyResult = oShell.LogEvent(0, "Test Script Completed")</p><h3>Methods and properties of the Network class</h3> <p>As we have already seen, VBS scripts can work with the Windows shell, but this is not their only possibility. With the Network class, you can access and manipulate network objects. Let's take a closer look at the Network class:</p><p>ComputerName " return the computer name; UserDomain " return the domain name; UserName " return the username; EnumNetworkDrives " return a list of mapped network drives; MapNetworkDrive( <LocalName>, <RemoteName>, ) " network resource connection; RemoveNetworkDrive( <Name>, , ) " disconnecting a network resource; EnumPrinterConnections " return a list of network printers; AddWindowsPrinterConnection( <PrinterPath>) "network printer connection; AddPrinterConnection( <LocalName>, <RemoteName>[, UpdateProfile, User, Password] " connect a network printer to the specified port; RemovePrinterConnection( <Name>[,Force, UpdateProfile]) " disable network printer; SetDefaultPrinter( <PrinterName>) " default printer selection;</p><p>Example. Using the methods and properties of the Network class.</p><p>" Create a Network Set object oNetwork = WScript.CreateObject("WScript.Network") " Print a message about the computer name WScript.Echo "Computer Name = " & oNetwork.ComputerName " Print a message about the current user name WScript.Echo "User Name = " & oNetwork.UserDomain & "\" & oNetwork.UserName " Map a network drive oNetwork.MapNetworkDrive "Z:" "\\Server\Share" " Get a collection of mapped network drives Set oDrives = oNetwork.EnumNetworkDrives " Display messages about mapped network drives For i=0 To oDrives.Count -1 step 2 WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1) Next " Remove network drive oNetwork.RemoveNetworkDrive "Z:" " Connecting a network printer oNetwork.AddPrinterConnection "LPT1", "\\Server\Printer" " Setting the default printer oNetwork.SetDefaultPrinter "\\Server\Printer" " Getting a collection of connected printers Set oPrinters = oNetwork.EnumPrinterConnections</p><h3>Methods and properties of the FileSystemObject class</h3> <p>Very often in scenarios there are such cases when it is necessary to create, delete, move or change something on the computer disk. This task can be solved by the FileSystemObject class, designed to work with <a href="https://unitarmy.ru/en/zvuk-i-karty/puppy-linux-ustanovka-iz-windows-ustanovka-puppyrus-a-pra-na-fleshku-ili-hdd-zhestkie-diski.html">file system</a>. The following are the objects that this class can create:</p> <ul><li>FileSystemObject - the main object that allows you to create, delete, manage drives, folders and files in general;</li> <li>Drive - an object that allows you to collect information about the disks of the system;</li> <li>Drives - an object that stores a list of system drives;</li> <li>Folder - an object that allows you to create, delete, move folders, as well as collect information about them and their contents;</li> <li>Folders - an object that contains a list of subfolders of the specified folder;</li> <li>File - an object that allows you to create, delete, move files, and collect information about them;</li> <li>Files - an object that contains a list of files in the specified folder;</li> <li>TextStream - an object that allows you to read and create text files.</li> </ul><p>Methods and properties of the FileSystemObject class (main object):</p><p>BuildPath( <Path>, <Name>) " adds a name to the specified path; GetAbsolutePathName( <PathSpec>) " returns the full path; GetBaseName( <Path>) " returns the name of the folder or file (without the " extension) in the specified path; GetDrive( <DriveSpec>) " creates a Drive object; GetDriveName( <Path>) " returns the name of the drive in the specified path; GetExtensionName( <Path>) " returns the extension of the file in " the specified path; GetFile( <FileSpec>) " creates a File object; GetFileName( <PathSpec>) "returns the filename (without extension)" in the specified path; GetFolder( <FolderSpec>) " creates a Folder object; GetParentFolderName( <Path>) " returns the name of the folder in which the " file or folder is stored at the specified path; GetSpecialFolder( <FolderSpec>) " creates a Folder object to the specified " service folder; GetTempName " returns a randomly generated " filename; DriveExists( <DriveSpec>) " checks for disk existence; FolderExists( <FileSpec>) " checks if the folder exists; CopyFolder( <Source>, <Destination>[, Overwrite]) " copies the folder; MoveFolder( <Source>, <Destination>) " moves the folder; DeleteFolder( <FolderSpec>[, Force]) "deletes a folder; CreateFolder( <FolderName>) " creates a folder; FileExists( <Filespec>) " checks for the existence of a file; CopyFile( <Source>, <Destination>[, Overwrite]) " copies the file; MoveFile( <Source>, <Destination>) " moves the file; DeleteFile( <FileSpec>[, Force]) " deletes the file; CreateTextFile( <FileName>[, Overwrite, UnioCode]) " creates a text file; OpenTextFile( <FileName>[, IOMode, Create, Format]) "opens a text file for reading or writing.</p><p>The Drives, Folders, and Files objects of the FileSystemObject class store information about drives, folders, and files, and are primarily used to gather information about the file system. They have only two properties:</p><p>Count " returns the number of items in the collection; Item( <ObjectName>) " returns the record at the specified index from the collection (not used), " a For Each loop is used to iterate over the elements of the collection.</p><p>To make it clearer what a collection of objects is, consider an example of displaying a list of files on the root of drive C:</p><p>" Creating an object of class FileSystemObject Set oFSO = CreateObject("Scripting.FileSystemObject") " Creating a Folder object Set oFolder = oFSO.GetFolder("C:\") " Getting a collection of files Set oFilesCollection = oFolder.Files " Getting the number of elements in the collection sResult = sResult & oFilesCollection.Count & " files in C:\" & vbCrLf " Read the attributes of each file in the collection. For Each oFile in oFilesCollection sResult = sResult & oFile.Name & vbTab sResult = sResult & oFile.Size & vbCrLf Next " Display the result to screen MsgBox(sResult)</p><p>The Drive object provides access to the properties of a local or network drive:</p><p>AvailableSpace " returns the amount of free disk space available to the user; DriveLetter " returns the drive letter; DriveType " returns the drive type; FileSystem " returns the file system type of the drive; FreeSpace " returns the amount of free disk space; IsReady " returns the availability of the disk; Path " returns the path to the drive; RootFolder " creates a Folder object pointing to the root of the drive; SerialNumber " returns the serial number of the disk; ShareName " returns the network name of the disk; TotalSize " returns the capacity of the disk in bytes; VolumeName " returns or sets the label of the disk.</p><p>The Folder object provides access to all properties of the folder, and also allows you to perform actions on it:</p><p>Attributes " returns the attributes of the folder; DateCreated " returns the date the folder was created; DateLastAccessed " returns the date the folder was last accessed; DateLastModified " returns the date the folder was modified; Drive " returns the drive letter on which the folder is located; Files " returns the folder's collection of files; IsRootFolder " returns True if the folder is the root of the drive; Name " returns the name of the folder; ParentFolder " creates a Folder object pointing to the " parent folder; Path " returns the path to the folder; ShortName " returns the name of the folder in 8.3 format; ShortPath " returns the path to the folder in 8.3 format; Size " returns the size of the folder; SubFolders " returns a collection of subfolders; Type " returns the folder type; Copy( <Destination>[, Overwrite]) " copies the folder; Move( <Destination>) " moves the folder; Delete( <Force>) " deletes the folder; CreateTextFile( <FileName>[, Overwrite, UniCode])" creates a text file in the folder.</p><p>The File object is similar to the Folder object - it provides access to all the properties of the file, and also allows you to perform actions on it:</p><p>Attributes " returns the file's attributes; DateCreated " returns the creation date of the file; DateLastAccessed " returns the date the file was last accessed; DateLastModified " returns the date the file was modified; Drive " returns the drive letter on which the file is located; Name " returns the name of the file; ParentFolder " creates a Folder object pointing to the " parent folder; Path " returns the path to the file; ShortName " returns the file name in 8.3 format; ShortPath " returns the path to the file in 8.3 format; Size " returns the size of the file; Type " returns the file type; Copy( <Destination>[, Overwrite]) " copies the file; Move( <Destination>) " moves the file; Delete( <Force>) " deletes the file; OpenAsTextStream() " opens a text file for reading or writing.</p><p>The TextStream object is a tool for accessing the contents of a file. With it, you can read and modify the file:</p><p>AtEndOfLine " indicates whether the end of the line has been reached; AtEndOfStream " indicates whether the end of the line has been reached; Column " returns the number of the column where the read cursor is; Line " returns the number of the line where the read cursor is; Close " closes the file - releases it for other processes; Read( <CharactersNumber>) " reads the specified number of characters, starting from position " of the read cursor; ReadAll " reads the entire file; ReadLine " reads the line where the read cursor is located; Skip( <CharactersNumber>) " skips the specified number of characters, starting from position " of the read cursor; SkipLine " skips the line where the read cursor is located; Write( <String>) " writes a line; WriteLine( <String>) " writes a line and advances the write cursor to the next line; WriteBlankLines( <Lines>)" writes the specified number of empty lines.</p><p>We got acquainted with all the methods and properties of the FileSystemObject class, consider an example of using this class:</p><p>" Setting code constants for system folders Const WindowsFolder = 0 Const SystemFolder = 1 Const TemporaryFolder = 2 " Setting code constants for types of access to a text file Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 "Creating an object of class FileSystemObject Set oFSO = CreateObject(" Scripting.FileSystemObject") " Get a collection of drives Set DrivesCollection = oFSO.Drives " Process each drive to get its label or network name For Each oDrive in DrivesCollection sResult = sResult & oDrive.DriveLetter & ": " If oDrive.DriveType = Remote Then sResult = sResult & oDrive.ShareName & vbCrLf ElseIf oDrive.IsReady Then sResult = sResult & oDrive.VolumeName & vbCrLf Else sResult = sResult & vbCrLf End If Next " Display results Wscript.Echo(sResult) " Create drive object C: Set oDrive = oFSO.GetDrive("C") sResult = oDrive.DriveLetter & ": - " " Get Drive Type C: Select Case oDrive.DriveType Case 0: sResult = sResult & "Unknown - " Case 1: sResult = sResult & "Removable - " Case 2: sResult = sResult & "Fixed - " Case 3: sResult = sResult & "Network - " Case 4: sResult = sResult & "CD-ROM - " Case 5: sResult = sResult & "RAM Disk - " End Select " Determine if a drive is available and get its properties If oDrive.IsReady Then sResult = sResult & "Ready" & vbCrLf sResult = sResult & "FileSystem is " & oDrive.FileSystem & vbCrLf sResult = sResult & "Available Space: " & _ FormatNumber( oDrive.AvailableSpace/1024, 0) & " Kbytes" Else sResult = sResult & "Not ready" End If " Print results to screen Wscript.Echo(sResult) " Create a service folder object (Windows temporary files folder) Set oTempFolder = oFSO. GetSpecialFolder(TemporaryFolder) " Create a text file object (and create it at the root of the C: drive) Set oFile = oFSO.CreateTextFile("C:\TestFile.txt", True) " Write to a text file oFile.WriteLine("This is a test.") oFile.WriteLine(sResult) " Closing a text file and releasing it for other processes oFile.Close " Checking for a file in the temporary folder <a href="https://unitarmy.ru/en/windows-7/prilozhenie-android-file-transfer-dlya-windows-xp-android-file-transfer-programma.html">Windows files</a>, deleting this file If oFSO.FileExists(oFSo.BuildPath(oTempFolder.Path, "TestFile.txt")) Then _ oFSO.DeleteFile(oFSo.BuildPath(oTempFolder.Path, "TestFile.txt")) " Creating a Set file object oFile = oFSO.GetFile("C:\TestFile.txt") " Move file to Windows Temporary Files folder oFile.Move(oFSo.BuildPath(oTempFolder.Path, "TestFile.txt")) " Change file attribute If oFile. Attributes and 32 Then oFile.Attributes = oFile.attributes - 32 Wscript.Echo("Archive bit is cleared") Else oFile.Attributes = oFile.attributes + 32 Wscript.Echo("Archive bit is set") End If sResult = oFile .Path & vbCrLf & oFile.DateLastModified & ":" & vbCrLf " Create a stream object by opening a file for reading Set oTestFile = oFSO.OpenTextFile(oFile.Path, ForReading, False) " Read stream until end is encountered Do While oTestFile .AtEndOfStream<>True sResult = sResult & oTestFile.ReadLine Loop " Closing a text file and releasing it for other processes oTestFile.Close " Printing a message to the screen Wscript.Echo(sResult)</p><h3>Scenario "Delete old files"</h3> <p>This script is designed to clean the system of obsolete files in Windows temporary directories and user profiles. In this example, you can see how almost all of the above constructions work: script structure, variable names, working with arrays and collections, manual error handling, reading system variables, creating a text file of the script log, working with the file system, using procedures.</p><p> " ==== Script Information Header ==== " script name: Purge Temp " version: 1.0 " date: 16.07.08 " author: Bochkarev Vitaly " description: Script removes obsolete temporary files from computer " ==== Script Main Logic ==== " Enable manual error handling On Error Resume Next " Time interval constant when files are considered out of date Const PurgeTime = 14 " days " Exceptions are user profiles that should not be handled Dim aExceptions(3) aExceptions(0) = " Default User" aExceptions(1) = "LocalService" aExceptions(2) = "NetworkService" aExceptions(3) = "All Users" " Creating shell and file system objects Set oShell = CreateObject("wscript.shell") Set oFSO = CreateObject ("Scripting.Filesystemobject") " Defining service folder paths sProgramFiles = oShell.ExpandEnvironmentStrings("%ProgramFiles%") sWinDir = oShell.ExpandEnvironmentStrings("%WinDir%") sWinTempFolder = sWinDir & "\Temp" sDocuments = "C:\ Documents and Settings" " Creating a script log sLogFileName = sWinTempFolder & "\PurgeTemp_" & Date sLogFileName = Replace(sLogFileName, ".", "_") sLogFileName = Replace(sLogFileName, "/", "_") Set oLogFile = oFSO.CreateTextFile(sLogFileName & ".log",true) oLogFile.WriteLine "========== Start purging ==========" " Clearing the Windows temp folder oLogFile.WriteLine vbCrLf & "========== Windows Temporary folder ==========" PurgeFolder(sWinTempFolder) " Purge user profile temp folder and Internet files oLogFile.WriteLine vbCrLf & _ "===== ===== Users Temporary folder and Users Temporary Internet Files ==========" Set oDocuments = oFSO.GetFolder(sDocuments) Set colProfiles = oDocuments.SubFolders For Each oProfile In colProfiles bFlag = false For Each sException in aExceptions if InStr(oProfile.Path,sException) > 0 then bFlag = true exit for end if Next If bFlag = False Then PurgeFolder(oProfile.Path & "\Local Settings\Temp") PurgeFolder(oProfile.Path & "\Local Settings\Temporary Internet Files") End If Next " Clear NOD32 Quarantine oLogFile.WriteLine vbCrLf & "========== NOD32 Quarantine ==========" sQuarantine = sProgramFiles & "\Eset \Infected" PurgeFolder(sQuarantine) " Closing the log file oLogFile.WriteLine vbCrLf & "========== Stop purging ==========" oLogFile.Close " Procedure PurgeFolder - deleting old files Sub PurgeFolder(sFolderPath) " Create a Folder object Set oFolder = oFSO.GetFolder(sFolderPath) " Get a collection of files Set colFiles = oFolder. Files " Process each file in the collection For each oFile in colFiles " Check if the file is stale If (Date-oFile.DateLastModified) > PurgeTime and (Date-oFile.DateCreated) > _ PurgeTime Then " Write a message to the oLogFile.Writeline script log oFile.Path & vbTab & oFile.DateCreated " Delete obsolete file oFSO.DeleteFile oFile.Path, True " Check for errors if err.Number<>0 then " Write error message to script log oLogFile.Writeline "-----> Error # " & CStr(Err.Number) _ & " " & Err.Description " Clear error Err.Clear end if " Pause at 20 milliseconds WScript.Sleep 20 End if Next " Get a collection of subfolders Set colSubFolders = oFolder.SubFolders " Process each subfolder For Each oSubFolder In colSubFolders " Recursively call the procedure for deleting old files - the routine calls " itself PurgeFolder(oSubFolder.Path) " Check the size of the folder If oSubFolder.Size = 0 Then " Write message to script log oLogFile.Writeline oSubFolder.Path & vbTab & oSubFolder.DateCreated " Delete empty folder oFSO.DeleteFolder oSubFolder.Path " Check for errors If err.Number<>0 then " Write error message to script log oLogFile.Writeline "-----> Error # " & CStr(Err.Number) _ & " " & Err.Description " Clear error Err.Clear End if End if Next End Sub</p><p>So, we got acquainted with the basics of Visual Basic Script scripting. Let's summarize and define the advantages and disadvantages of such scenarios:</p> <ul><li>scripts do not require compilation and their code can be edited at any time;</li> <li>VBS scripts are practically unlimited in functionality and can use various system libraries and objects of other applications;</li> <li>VBS files can be executed both in the console and in windowed mode, so the user can control the visibility of the script execution progress;</li> <li>VBS scripts allow you to use custom procedures and functions;</li> <li>this language is ideal for working with string and numeric variables, dates, as well as for processing <a href="https://unitarmy.ru/en/windows/programma-dlya-sravneniya-2-failov-programma-dlya-sravneniya-tekstovyh-failov.html">text files</a>, system and domain management;</li> <li>VBS scripts are difficult to write and require programming skills;</li> <li>such scripts only work in <a href="https://unitarmy.ru/en/kompyuter-zhelezo/simbian-7-os-symbian-operacionnaya-sistema-dlya-sotovyh-telefonov-smartfonov-i.html">operating systems</a> Windows family.</li> </ul><p>Vitaly Bochkarev</p> <h2>External links</h2> <p>Section of external links, that is, links to other sites to which this resource has nothing to do. In addition, the site owner does not bear any responsibility for the availability of these resources and for their content.</p> <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast_after?t44.1;r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";h"+escape(document.title.substring(0,150))+ ";"+Math.random()+ "border='0' width='1' height='1' loading=lazy loading=lazy>");</script> </div> </article> <div class="post-share"> <div>Share with friends or save for yourself:</div> <script src="//yastatic.net/es5-shims/0.0.2/es5-shims.min.js"></script> <script src="//yastatic.net/share2/share.js"></script> <div class="ya-share2" data-services="collections,vkontakte,facebook,odnoklassniki,moimir,gplus,viber,whatsapp,skype,telegram"></div> <br> <div id="post-ratings-14689-loading" class="post-ratings-loading"> <img src="https://unitarmy.ru/wp-content/plugins/wp-postratings/images/loading.gif" width="16" height="16" class="post-ratings-image" / loading=lazy loading=lazy>Loading...</div> </div> <div class='yarpp-related'> <div class="related"> <div class="headline">Recommended related articles</div> <div class="items"> <div class="item"> <div class="item__image"> <picture> <source media="(max-width: 479px)" srcset="/wp-content/themes/unitarmy.ru/cache/945f81849_460x250.png"><img src="/uploads/ed08b13831d51531eeb6bca21013e13c.jpg" width="240" height="240" alt="ModPack Zeus002 download mods here World Of Tanks mod pack Download mod pack for here" / loading=lazy loading=lazy></picture> </div> <div class="item__title"><a href="https://unitarmy.ru/en/zvuk-i-karty/modpack-zeus002-skachat-mody-vot-world-of-tanks-mod-pak-modpack-zeus002-skachat-mody-vot-world-of-tanks.html">ModPack Zeus002 download mods here World Of Tanks mod pack Download mod pack for here</a></div> </div> <div class="item"> <div class="item__image"> <picture> <source media="(max-width: 479px)" srcset="/wp-content/themes/unitarmy.ru/cache/945f81849_460x250.png"><img src="/uploads/bbae6fa7d2f703308ce39bba743503f7.jpg" width="240" height="240" alt="Recovery of equipment and crew" / loading=lazy loading=lazy></picture> </div> <div class="item__title"><a href="https://unitarmy.ru/en/bezopasnost/wot-vosstanovlenie-tehniki-vosstanovlenie-tehniki-i-ekipazha.html">Recovery of equipment and crew</a></div> </div> <div class="item"> <div class="item__image"> <picture> <source media="(max-width: 479px)" srcset="/wp-content/themes/unitarmy.ru/cache/945f81849_460x250.png"><img src="/uploads/591973be997baa08dd5cc70140666337.jpg" width="240" height="240" alt="Playing a WoT replay from a file" / loading=lazy loading=lazy></picture> </div> <div class="item__title"><a href="https://unitarmy.ru/en/bezopasnost/ne-pokazyvaet-replei-v-world-of-tanks-vosproizvodim-replei-wot-iz-faila-nizhe.html">Playing a WoT replay from a file</a></div> </div> </div> </div> </div> </main> <aside class="sidebar"> <div class="amulets sidebar__section"> <div class="headline">Popular Articles</div> <ul class="amulets__list"> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/windows-8-1/kak-vernut-prodannuyu-premium-tehniku-v-wot-vosstanovlenie-tehniki-i-ekipazha-kak.html">Recovery of equipment and crew How to restore a premium tank in wot</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/brauzery/izmenit-imya-v-tankah-zashchiti-akkaunt-i-poluchi-svobodnyi-opyt-osnovnye.html">Protect your account and get free experience!</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/windows/world-of-tanks-shema-bronirovaniya-tankov-ih-uyazvimye-mesta-igra-world-of-tanks.html">World of tanks: armor scheme for tanks, their vulnerabilities</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/google-chrome/koefficienty-farma-wot-blitz-luchshii-premium-tank-v-wot-chto-eto-takoe-farmit.html">The best premium tank in WoT</a></li> <li class="amulets__list-item"><a href="https://unitarmy.ru/en/windows-8-1/replei-world-of-tanks-podrobnaya-instrukciya-luchshee-shou-dlya-tankistov---lrn-kak.html">The best show for tankers - OSR: how to send a replay?</a></li> </ul> <div class="amulets__all"><a href="https://unitarmy.ru/en/">See all articles</a></div> </div> <div class="sidebar__section sidebar__widget" id="recent-posts-3"> <div class="headline">Latest articles:</div> <ul> <li> <a href="https://unitarmy.ru/en/obzory/kak-otpravit-zapis-boya-v-lrn-replei-world-of-tanks-podrobnaya-instrukciya.html">Replays World of Tanks detailed instructions</a></li> <li> <a href="https://unitarmy.ru/en/bezopasnost/installpack-skachat-besplatno-russkaya-versiya-installpack-skachat-vse-programmy-iz-odnogo.html">Installpack download all programs from one interface Download software pack for windows 7</a></li> <li> <a href="https://unitarmy.ru/en/noutbuki-i-netbuki/besplatnoe-obshchenie-skype-viber-whatsapp-i-drugie---gusarev-journal-zhzh-pohozhie.html">Similar analogues of WhatsApp Apps like whatsapp</a></li> <li> <a href="https://unitarmy.ru/en/google-chrome/kak-nastroit-programmu-mhotspot-na-vindovs-8-osobennosti-nastroiki-i-ispolzovaniya-programmy-mhots.html">Features of setting up and using the mHotspot program</a></li> <li> <a href="https://unitarmy.ru/en/windows-8-1/izmenilas-startovaya-stranica-yandeksa-chto-delat-kak.html">How to set Yandex as the start page in the browser</a></li> <li> <a href="https://unitarmy.ru/en/noutbuki-i-netbuki/kak-nastroit-gugl-hrom-pod-sebya-gugl-hrom-kak-nastroit.html">Google Chrome: how to customize the browser for yourself Necessary settings in Google Chrome</a></li> <li> <a href="https://unitarmy.ru/en/mozilla-firefox/hola-rasshirenie-dlya-android-rasshirenie-hola-skachat-dlya-lyubogo.html">Hola extension: download for any browser</a></li> <li> <a href="https://unitarmy.ru/en/razlichnye-problemy/gta-5-na-maksimalnyh-nastroikah-grand-theft-auto-v-grafika-rukovodstvo-po-nastroikam.html">Gta 5 at maximum settings</a></li> <li> <a href="https://unitarmy.ru/en/windows-8/zaregistrirovatsya-na-facebook-bez-elektronnoi-pochty.html">Facebook registration and login to your page</a></li> <li> <a href="https://unitarmy.ru/en/razlichnye-problemy/pochemu-gta-4-ne-zapuskaetsya-posle-ustanovki-reshenie-problem.html">Why gta 4 won't start after installation</a></li> </ul> </div> <div class="sidebar__section sidebar__widget" id="text-2"> <div class="textwidget"> </div> </div> </aside> </div> <footer class="footer"><nav class="footer__nav nav"><ul> <li class="menu-item type-post_type object-page "><a href="https://unitarmy.ru/en/feedback.html" itemprop="url">Feedback</a></li> <li class="menu-item type-post_type object-page "><a href="https://unitarmy.ru/en/sitemap.xml" itemprop="url">Site Map</a></li> <li class="menu-item type-post_type object-page "><a href="" itemprop="url">Advertising</a> <li class="menu-item type-post_type object-page "><a href="https://unitarmy.ru/en/feedback.html" itemprop="url">About the site</a></li> </ul></nav><div class="footer__inner"><div class="footer__copyright" style="background:none;"> <div class="footer__copyright-title1"></div> <p>© 2023. All rights reserved <br />Basics of working on a personal computer</p> </div><div class="footer__counters"></div><div class="footer__info"><p></p></div></div></footer> </div> </div> <script type="text/javascript" defer src="https://unitarmy.ru/wp-content/script.js"></script> </body> </html>