VBScript
What is VBScript?
VBScript is a scripting programming language. The format can vary, the format .vbs
or .vbe
can be used. VBS is the acronym for Visual Basic Script. As for syntax, it is very similar to other languages. In particular, however, VBS is a particularly useful language for those who have the Windows operating system, because it allows us to create various forms in a simple and uncomplicated way.
VBScript
Let's start with the easiest thing, the msgbox
function, which creates a window:
msgbox message, struct, title
message
- Specifies the message to display in the window (in quotes).struct
- Specifies the window structure (see below).title
- Specifies the title to give to the window, to be displayed in the title bar (also in quotes).
Instead of struct
, you must specify fig
+ butt
(figure + buttons).
Instead of fig
:
Write | Or enter the value | To display |
vbCritical |
16 | |
vbQuestion |
32 | |
vbExclamation |
48 | |
vbInformation |
64 |
Specifying 0 does not insert any image. If vbSystemModal
is set (value 4096) the window is in the foreground.
Instead of butt
:
Write | Or enter the value | To display the buttons |
vbOkOnly |
0 | OK |
vbOkCancel |
1 | OK - Annulla |
vbAbortRetryIgnore |
2 | Abort - Retry - Ignore |
vbYesNoCancel |
3 | Yes - No - Cancel |
vbYesNo |
4 | Yes - No |
vbRetryCancel |
5 | Retry - Cancel |
So, in order to display:
You should write:
msgbox "Eliminare il file di sistema C:\WINDOWS\system32\cscc.exe?", vbCritical + vbYesNo, "Errore"
or:
msgbox "Eliminare il file di sistema C:\WINDOWS\system32\cscc.exe?", 16 + 4, "Errore"
In this case the two values can be added:
msgbox "Eliminare il file di sistema C:\WINDOWS\system32\cscc.exe?", 20, "Errore"
As in all programming languages, comments can also be inserted in VBS files. Just insert a character: '
.
' comment
or:
various_instructions ' comment
With this symbol you can add comments, even at the end of the line.
Example:
msgbox "gloogloo" ' Display "gloogloo" message.
The comment will be ignored by the system. Another example (at the beginning of a file):
' *--------------------------------*
' Name: filename.vbs
' Author: File Author
' Description: File Description...
' *--------------------------------*
Objects are special entities that allow us to perform functions to manage certain resources. For example, the Scripting.FileSystemObject
object allows us to use functions to manage files and directories. Objects are usually saved to variables using the set
statement. Example (CreateObject()
is used to create the object):
set fso = CreateObject("Scripting.FileSystemObject")
For example, to delete a file/directory you use the DeleteFile()
or DeleteFolder()
function using this syntax:
FSO.DeleteFile file_path, force_delete
FSO.DeleteFolder directory_path, force_delete)
file_path
/folder
is a string (therefore enclosed in quotes) containing the path to the file or directory. Instead of force_delete
specify True
if you also want to delete read-only files/folders. Ex:
set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFile "C:\Fillet.txt"
You need permissions to delete some files or directories.
You can use if
when you want to create conditions, based on which the processor will decide which commands to execute. Example:
a = 12
b = 6
if b * 2 = a then msgbox "2b = a" else msgbox "b is not half of a"
or:
a = 12
b = 6
if b * 2 = a then
msgbox "2b = a"
else
msgbox "b is not half of a"
end if
end if
tells us that the condition is finished.
It is possible to find out which button was pressed (in a msgbox
) by assigning the msgbox
function to a variable, and then using a condition.
Note that if you use an assignment, the function arguments (in this case msgbox
) must be in parentheses (we have already seen this with the CreateObject
function).
Button = msgbox("Are you a chimpanzee?", vbCritical + vbYesNo, "System error")
if Button = butt then ...
Al posto di butt
:
Write | Or enter the value | To execute instruction(s) if the following button is pressed |
vbOk |
1 | OK |
vbCancel |
2 | Cancel |
vbAbort |
3 | Abort |
vbRetry |
4 | Retry |
vbIgnore |
5 | Ignore |
vbYes |
6 | Yes |
vbNo |
7 | No |
So:
Button = msgbox("Are you a chimpanzee?", vbCritical + vbYesNo, "System Error")
if Button = vbYes then
msgbox "Strange! You are too ugly!", vbExclamation + vbOkOnly, "System error"
elseif Button = vbNo then
msgbox "I knew it! You must be a gorilla.", vbExclamation + vbOkOnly, "System Error"
else
msgbox "Error 0x0CC49: All personal documents have been deleted", vbCritical + vbOkOnly, "System Error"
end if
elseif
creates the condition only if the previous one is false, it would literally mean else if ...
. Example:
a = "l"
b = "a"
if a = "u" then
msgbox a
elseif b = "e" then
msgbox b
else
msgbox a & b
end if
Look at this other example:
a = "l"
b = "a"
if a = "u" then
msgbox a
if b = "e" then
msgbox b
else
msgbox a & b
end if
In the first case it executes msgbox b
only if the previous condition is false and the condition b = "e"
is true, while in the second case it executes msgbox b
even if the previous condition is true.
Another example:
if a = b then
msgbox a & " = " & b
elseif a = c then
msgbox a & " = " & c
end if
Which is similar to:
if a = b then
msgbox a & " = " & b
else
if a = c then
msgbox a & " = " & c
end if
end if
Remember: Always put then
after a condition!
NB: The example would be incorrect without defining, that is, giving a value to the variables a
, b
and c
.
Arithmetic signs (most important ones):
=
- Equal to / assignment<>
- Unequal to>
- Greater than<
- Less than+
- Plus-
- Minus/
- Divided by*
- Times
Example:
a = 5
b = 10
c = 15
if a + b = c then
msgbox "a + b = c"
end if
if a <> c and a < c then
msgbox "a is different from c and less than c."
end if
if 2 * c / 3 = b then
msgbox "2c : 3 = b"
end if
if a <> 12 or a <> 5 then
msgbox "a is different from either 12 or 5."
end if
and
specifies that both conditions must be satisfied;
or
specifies that only one of the conditions must be satisfied.
You use dim
to declare variables, that is, to say that those variables will be assigned a value:
dim variable1, variable2, variable3
variable1 = value1
variable2 = value2
variable3 = value3
To make dim
mandatory before defining the variable value, add this string:
option explicit
Example:
option explicit
dim a, b, c
a = "Hi goofy"
b = "UHUH"
c = "Doge"
To copy a file, this is the syntax:
FSO.CopyFile source, destination
Example:
set a = CreateObject("Scripting.FileSystemObject")
a.CopyFile Wscript.ScriptFullName, "C:\uasasf.vbs"
Wscript.ScriptFullName
is a string variable containing the path and name of the executed vbs file. So running this program duplicates the file to the desired destination.
To perform certain functions, we use the Wscript.Shell
object (which we will abbreviate to WSC
). For example, to write to the *
registry:
WSC.RegWrite path_to_key_or_value, data, type
*
What is the registry? To get there, just do Start > Run > REGEDIT. Here you can change the system settings, but be careful! If a key is changed or deleted inappropriately, the system may suffer.
Instead of path_to_key_or_value
, you must specify the path to the key or value to be created (including the name of the key/value), instead of data
, you must enter the value to be given in case a value is created, instead of type
, specify the type of value, "REG_SZ"
is for strings, "REG_DWORD"
is for integers.
If a slash (\
) is specified at the end of the path, it creates a key, so data
and type
must be omitted. If the slash is not specified, a value is created.
Example:
set WSC = Wscript.CreateObject("Wscript.Shell")
WSC.RegWrite "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\myValue", "C:\WINDOWS\system32\set.exe | more", "REG_SZ"
Create the value myValue
in the registry path HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
and give it to the value the data C:\WINDOWS\system32\set.exe | MORE
and the REG_SZ
value type.
NB: HKLM
stands for HKEY_LOCAL_MACHINE
; to write to the local machine you need to have permissions.
Now you want to see if the value was created successfully? To do this you have to read the system registry; this is the syntax:
WSC.RegRead(pathtovalue)
Instead of pathtovalue
specify the path to the value to read.
Example:
set wsc = Wscript.CreateObject("Wscript.Shell")
wsc.RegWrite "HKCU\Software\Windows\Microsoft\Value", "set", "REG_SZ"
Value = wsc.RegRead("HKCU\Software\Windows\Microsoft\Value")
if Value = "set" then
msgbox "Value created successfully!", vbInformation + vbOkOnly, "HKCU\Software\Microsoft\Windows\Value"
else
msgbox "The value was not created correctly.", vbInformation + vbOkOnly, "HKCU\Software\Microsoft\Windows\Value"
end if
Creates the value Value
in the path HKEY_CURRENT_USER\Software\Microsoft\Windows
with the data set
and the value type REG_SZ
, and reads it to see if the value was created successfully.
Note: The HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\
key contains all the paths to the programs or files to run when Windows starts.
Syntax to delete a value or key:
WSC.RegDelete(path_to_key_or_value)
We learned how to delete files before, but how do you create them? Here's the syntax:
set TF = FSO.CreateTextFile(filepath)
This is the syntax to create a file, but, in order to write text to it, add:
TF.WRITELINE text
You can also continue typing at the line break, repeating the string you want to write. To leave the line blank, simply do not specify text
.
Example:
set fso = CreateObject("Scripting.FileSystemObject")
set File = fso.CreateTextFile("C:\Folder\Virus.txt")
File.WriteLine "How to create a virus"
File.WriteLine
File.Writeline "To create a virus go to Google and type 'How to create a virus'."
Creates the C:\Virus.txt
file by writing the following lines:
How to create a virus
To create a virus go to Google and type 'How to create a virus'.
You need permissions to create files in certain paths.
To execute a file or open a directory, this is the syntax:
WSC.Run file_or_directory
Example:
set a = Wscript.CreateObject("Wscript.Shell")
a.Run "notepad"
Opens the infamous program for writing and programming (Notepad). Instead of notepad, an external DOS command or any other application can be specified.
Unlike DOS, where %%
is used to expand variables, in VBS the value of a variable is evaluated every time it is found in any expression. With the variables time
and date
, which are predefined, we can for example write:
msgbox "Sono le " & time & " del giorno " & date, 0 + vbOkOnly, "Ora e data"
Result:
Obviously, instead of the time and date written above, the current time and date will be displayed.
To make the script pause for a certain time, this is the syntax:
Wscript.Sleep time
Instead of time
specify the script pause in milliseconds (without quotes).
Example:
msgbox "IN 5 MINUTES YOUR" & vbNewLine & "OPERATING SYSTEM WILL DIE!", vbCritical + vbOkOnly, "Errore del sistema"
Wscript.Sleep 300000
set p = CreateObject("Scripting.FileSystemObject")
set d = p.GetFile("C:\WINDOWS\*.*")
d.Delete
Displays the message IN 5 MINUTES YOUR OPERATING SYSTEM WILL DIE!
and blocks the script for 5 minutes (300000 milliseconds), then deletes all files in C:\WINDOWS
.
NB: vbNewLine
is used to start a new line.
How to run one or more instructions infinitely (until the wscript.exe process is killed with Task Manager)? Here is the syntax:
do
instructions
loop
This way when it reaches loop
it returns to do
, executing the instructions infinitely. If instead you want to execute the instructions only as long as a condition is true, add while
to do
:
do while condition
instructions
loop
It executes the instructions if the condition is true, if the condition is already false it does not execute them even once. Instead like this:
do
instructions
loop condition
When it reaches loop
it returns to do
only if the condition is true, so it executes the statements even if the condition is not true, even if it repeats them only once.
Example:
do
hello = msgbox "Are you crazy?", 0 + vbYesNo, "Just a question"
loop while hello <> vbYes
msgbox "You said yes, fool!", 0 + vbOkOnly, "Just a question"
Executes the msgbox
function and repeats it if the user does not respond yes.
How to make the user enter an input or text? The instruction is inputbox
:
inputbox message, title, input_example
NB: To provide an input example you must specify the title.
To record the input:
variable = inputbox(arguments)
So that the input can be used at a later time.
With the inputbox
you can create a naive way to protect the file with a password or password together with do while ... loop
. Example:
a = ""
do while a <> "PASSPASS"
a = inputbox("Enter your password here to continue:", "Program", "Password")
loop
msgbox "Welcome to the program ... blah blah blah ..."
As long as the input is not PASSPASS
it will always prompt for the password. If the input is no longer unequal to PASSPASS
it executes the msgbox
function.
Warning: in this way the password is very traceable: it is enough for one to open the file with notepad...
How to make a document write itself while the user reads? First of all you need to run Notepad or another writing program, like WordPad, then you need to simulate the pressing of the keys, like this:
set o = Wscript.CreateObject("Wscript.Shell")
o.Run "notepad" ' Or "wordpad"
Wscript.Sleep 3000 ' Let's wait for Notepad to load
o.SendKeys "GWAHAHA!!" ' The specified text will be written
This way, whatever you want will be written while the user reads.
These are the other keys that can be simulated (NB: the keys can be simulated even if there is no text file, in fact if the user closes the text file, the system continues to "write" or "press" keys):
- Backspace =
{BACKSPACE}
,{BKSP}
or{BS}
- Enter =
{ENTER}
oppure~
- Up arrow =
{UP}
- Down arrow =
{DOWN}
- Left arrow =
{LEFT}
- Right arrow =
{RIGHT}
- Caps lock (the padlock) =
{CAPSLOCK}
- Num lock =
{NUMLOCK}
- Scroll lock =
{SCROLLLOCK}
- Tab (The tiny arrows that go left and right) =
{TAB}
- Esc =
{ESC}
- Page up =
{PGUP}
- Page down =
{PGDN}
- Home (the oblique arrow) =
{HOME}
- End =
{END}
- Ins =
{INSERT}
oppure{INS}
- Del =
{DELETE}
oppure{DEL}
- Print screen =
{PRTSC}
- Pause Break =
{BREAK}
- F1 =
{F1}
- F2 =
{F2}
- F3 =
{F3}
- F4 =
{F4}
- F5 =
{F5}
- F6 =
{F6}
- F7 =
{F7}
- F8 =
{F8}
- F9 =
{F9}
- F10 =
{F10}
- F11 =
{F11}
- F12 =
{F12}
- Alt =
% -
example: Alt + 0160 =%(0160)
- Ctrl =
^ -
example: Ctrl + V =^V
- Shift (the fat arrow that goes up, so to speak) =
+ -
example: Shift + lol =+{lol}
To simulate that it is a human writing, use enough Wscript.Sleep
for each letter too! Pretend that it makes some mistakes and then correct them with the {BACKSPACE}
! You will scare the user!!
Warning: the characters %
, ^
and +
will not be displayed if added alone. For example, in order to show %
+{5}./p>
Example:
set wsc = Wscript.CreateObject("Wscript.Shell")
do
wsc.SendKeys "{F1}"
loop
Opens the online help forever (GWAHAHAHA!!).
NB: Limit your nastiness, I know you would already like to build a VBS file to send to a friend of yours to scare him and annoy him, but these functions can also be very useful for everyday use.
This is the code to shut down the computer:
set ShutD = GetObject("WinMGMTS: {(ShutDown)}//./Roor/CIMV2").ExecQuery("Select * From Win32_OperatingSystem Where Primary=True")
for each i in ShutD
i.ShutDown()
next
To reboot the system, replace i.ShutDown()
with i.Reboot()
.
We haven't learned yet some of these instructions, but don't worry.
To continue with the next command in case of error, add this string:
on error resume next
Which, instead of reporting the error, skips the command with the error, allowing the programmer to handle any errors.
Example:
on error resume next
dim wsc, Str
set wsc = CreateObject("Wscript.Shell")
do while Str <> "exit"
Str = inputbox("Enter the path in quotes to the file or folder. Click OK to open. To exit, type EXIT.", "Secret program", "Path")
if not Str = "exit" then wsc.Run(b)
loop
(dusted off from an old file, it is used to open files or folders knowing their location)
This way, if there is any run-time error (i.e. the file does not exist), it executes the next statement.
To find out if there was an error:
on error resume next
' ...
if err.number <> 0 then
' there has been an error
end if
Actually, to know if a file exists there is a specific function:
set fso = CreateObject("Scripting.FileSystemObject")
if fso.FileExist("C:\myFile.txt") then
' File exists
else
' File does not exist
end if
To know the day or month: the variable for the current second is Second(Now)
, for the minute is Minute(Now)
, for the hour is Hour(Now)
, for the day is Day(Now)
, for the month is Month(Now)
and for the year is Year(Now)
. Example:
if day(now) = 1 and month(now) = 1 then
msgbox "Happy New Year!", vbExclamation + vbOkOnly, "New Year"
end if
Executes the statement if the specified day and month are the current ones.
How to generate a random value? Like this:
randomize
var = int(rnd * n)
The rnd
function returns a pseudo-random value from 0 to 1. Multiplying by n
and converting it to an integer (with int
) we will obtain a pseudo-random integer value from 0
to n - 1
.
Example:
Randomize
Wscript.Echo 1 + int(rnd * 100)
Shoot a number from 1 to 100.
NB: Wscript.Echo
is used to display a message, similar to msgbox
.
The for
loop. What is a loop? Simply commands that repeat. We have already seen do loop
. Now let's see for, directly with an example.
dim i ' Let's declare the variable
for i = 0 to 9 step 1 ' We define i with the value of 0 and for each
' repetition it will increase by 1, up to 9
msgbox i + 1, 0 + vbOkOnly, "Counting from 1 to 10"
next ' Start the cycle again and increments i
This is a loop. Use exit for
to exit the loop immediately.
on error resume next
dim i
for i = 1 to 9 step 2
msgbox i + 1, 0 + vbOkOnly, "Counting"
if err.number <> 0 then exit for ' Exits the loop
next
Now let's see what arrays and matrices are. Arrays are an ordered set of values of the same type, integer, comma, string, etc. To recall a value of an array of n elements, you must specify its index, which can be at most n - 1, since the indices start from 0.
dim myArray, i, Wsc
set Wsc = Wscript.CreateObject("Wscript.Shell")
myArray = array("H", "e", "l", "l", "o", "!")
Wsc.Run "notepad"
Wscript.Sleep 1000
for i = 0 to UBound(myArray) step 1 ' UBound Returns the
' array size - 1 (upper bound)
Wsc.SendKeys myArray(i)
Wscript.Sleep 500
next
array()
is a function that constructs an array. In fact, this would be the standard way to define an array:
dim myArray(5), i
for i = 0 to 4 step 1
myArray(i) = i
next
What are matrices instead? They are nothing more than arrays of arrays, that is, two-dimensional arrays. Let me explain: instead of being an ordered list of values of the same type, such as integers and strings, they are ordered lists of arrays.
Example:
dim myMatrix(5, 5) ' 5x5 matrix
dim i, j
for i = 0 to 4 step 1
for j = 0 to 4 step 1
myMatrix(i, j) = i * j
next
next
The for each
is best for handling arrays, because the programmer does not need to know how big they are.Esempio:
dim myArray(10), myVar, i
for i = 0 to 9 step 1
myArray(i) = 100 / (i + 1)
next
myVar = 0
for each val in myArray
myVar = myVar + val
next
msgbox myVar
In the second loop (the for each
), val
is not the index, but a value of myArray
.
Comment below if you didn't understand something.
Comments