VBScript脚本语言学习(持续更新)

这个语言非常简单...花了我几个小时就基本上掌握了。由于它比批处理强大很多,所以我很喜欢。用于日常管理我的Windows操作系统。下面是我的学习记录下来的重点和总结。

A. 基础知识

    1. Cbool函数 把变量改成布尔型
    2. Cbyte函数 把变量转成0-255
    3. Ccur函数,Cdbl,Csng,转成浮点数前者只有小数点后4位
    4. Cdate函数转成日期
    5. Cint Clng 整数
    6. Cstr 转成字符串
    7. Redim preserve改变和保护数组
    8. ^是乘方 Mod是取模
    9. +和&连接字符串
    10. Is比较对象类型
    11. lcase转换成小写,ucase转大写
    12. const转成常量
    13. vbs中=就是==而=还是=
    14. vbs中不等于是<>
    15. vbCrlf是换行符

    

B. 语句类型

1. 条件语句

If 条件 Then
    ' ...
    ' ...
Elseif 条件 Then
    ' ...
    ' ...
Else
    ' ...
    ' ...
End If

例子:
Dim a, cnt
Const passwd = "123456"
cnt = 0
Do
    a = InputBox("请输入密码", "输入")
    If a = passwd And cnt <= 2 Then
        MsgBox "恭喜你, 密码正确"
        Exit Do
    ElseIf cnt < 2 Then
        MsgBox "密码错误,请再次输入"
        cnt = cnt + 1
    Else
        MsgBox "无法再次输入,再见"
        Exit Do
    End If
Loop


2. 选择语句

Select Case 变量
    Case x
        ' ...
    Case y
        ' ...
    Case z
        ' ...
    Case Else
        ' ...
End Select


3. 循环语句

1. Do ... Loop   离开用Exit Do
2. Do while 条件 ... Loop 离开用Exit Do
3. Do ... Loop While 条件 离开用Exit Do
4. For 变量 = x to x ... Next 离开用Exit For
5. For Each 变量 in 对象或数组 ... Next 离开用Exit For
6. Do ... Loop Until 条件 离开用Exit Do
6. While 条件 ... Wend

 

C. 关键命令和对象

a) CreateObject命令             

可以访问Windows内所安装的所有com对象并调用其中命令

b) WHS(这是用于解析VBS的宿主)常用对象

1. Scripting.FileSystemObject对象     提供一整套文件系统操作函数
2. Scirpting.Dictionary对象         用来返回存放键值对的字典对象
3. Wscript.Shell对象             提供一整套读取系统信息的函数,比注册表,查找文件路径,dos环境变量等

包含Run方法(空格加双引号,三引号也可以),run 函数有三个参数,第一个参数是你要执行的程序的路径,第二个程序是窗口的形式,0 是在后台运行;1 表示正常运行;2 表示激活程序并且显示为最小化;3 表示激活程序并且显示为最大化;一共有 10 个这样的参数我只列出了 4 个最常用的。 第三个参数是表示这个脚本是等待还是继续执行,如果设为了 true,脚本就会等待调用的程序退出后再向后执行

4. Wscript.NetWork对象             提供网络连接和打印机管理函数
注意: Scripting对象存放于SCRRUN.DLL,Wscript对象存放于WSHOM.ocx中

c) Set命令                将对象引用赋给变量使用Set关键字(对象是字符串,数值,布尔值之外的所有)

实例1:
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "notepad",,True '这里加上,,True后,关闭notepad才会运行接下去
objShell.Run "calc"


实例2:
' 读取注册表值
Set ws = wscript.CreateObject("wscript.shell")
v = ws.regread("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\Wechat")
wscript.echo v

' 写入值的数据
path = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\"
Set ws = wscript.CreateObject("wscript.shell")
t = ws.regwrite(path & "Wechat", "hello") '把指定值的数据改变
' 删除子键的值时注意加上\,否则会删除整个子键
path = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\hate"
Set ws = wscript.CreateObject("wscript.Shell")
Val = ws.regdelete(path)

d) On Error Resume Next                  告诉vbs运行脚本时跳过错误语句继续执行

e) FileSystemObject对象(FSO)

Drive对象: 包含存储设备信息
Drives对象: 提供物理和逻辑驱动器列表
File对象: 检查处理文件
Files集合: 提供文件夹中的文件列表
Folder对象: 检查和处理文件夹
Teststream对象: 读写文本文件

FSO常见方法:
BuildPath: 把文件路径信息添加到现有的文件路径上
CopyFile: 复制文件
CopyFolder: 复制文件夹
CreateFolder: 创建文件夹
CreateTextFile: 创建文本并返回TextStream对象
DeleteFile: 删除文件
DeleteFolder: 删除目录及内容
DriveExists: 确定驱动器是否存在
FileExists: 确定文件是否存在
FolderExists: 确定文件夹是否存在
GetAbsolutePathName: 返回文件或文件夹绝对路径
GetBaseName: 返回一个文件或文件夹的基本路径
GetDrive: 返回一个drive对象
GetDriveName: 返回驱动器名称
GetExtensionName: 返回拓展名
GetFile: 返回file对象
GetFileName: 返回文件夹中文件名
GetFolder: 返回Folder对象
GetParentFolderName: 返回文件夹的父文件夹
GetSpecialFolder: 返回指向一个特殊的文件夹对象指针 0: Windows目录 1:System32目录 2:Temp目录
GetTempName: 返回可以被CreateTextFile使用的随机产生的文件或文件夹名称
MoveFile: 移动文件
OpenTextFile: 打开一个存在的文件并返回TextStream对象

实例1:

On Error Resume Next
Dim fs, s, folderPath

Set fs = wscript.CreateObject("scripting.FileSystemObject")
If (fs.folderexists("C:\Users\Administrator\Desktop\ck")) Then
    s = "ck is available!"
Else
    Set foldr = fs.createfolder("C:\Users\Administrator\Desktop\ck")
    s = "ck doesn't exist and it has created now!"
End If
MsgBox s,,"提示"

实例2:

On Error Resume Next
Dim fs

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

fs.createfolder("C:\\Users\\Administrator\\Desktop\\ck")
'左复制到右,True意思是已存在则强制覆盖而不出错
fs.copyfolder "C:\\Users\\Administrator\\Desktop\\ck", "D:\\ck", True
fs.deletefolder("C:\\Users\\Administrator\\Desktop\\ck")
' 被教程坑了下,这里movefolder方法不支持跨盘操作
fs.movefolder "D:\ck", "D:\AppStore\ck"

实例3:

On Error Resume Next
Dim fs

Set fs = wscript.CreateObject("scripting.filesystemobject")
Set myFolder = fs.getfolder("C:\")
Set Files = myFolder.Files
For Each File In Files
    MsgBox File.Name
Next

实例4:
Dim fs

Set fs = wscript.CreateObject("scripting.filesystemobject")
Set wshshell = wscript.CreateObject("wscript.shell")
' 获取具体环境变量的值
osdir = wshshell.expandenvironmentstrings("%appdata%")
Set f = fs.getfolder(osdir)
wscript.echo f

实例5:
On Error Resume Next
Dim fs

Set fs = wscript.CreateObject("scripting.filesystemobject")
Set wfolder = fs.getspecialfolder(0) ' 返回Windows目录
Set wfolder = fs.getspecialfolder(1) ' 返回系统文件夹system32
Set wFolder = fs.getspecialfolder(2) ' 返回临时目录
wscript.echo wfolder


f) Object.SendKeys ”string“ 用于模拟键盘操作

string是要发送的内容,要加双引号,Shift用+来表示,Ctrl用^表示,Alt用%表示
假设同时按下Ctrl+C+E,则要用^(CE)来表示。至于+,^,%只要用{}括起来就可以表示其本身了
对于一些没有字符生成的控制键也需要用{},比如{ENTER} {UP} {ESC}...
重复的按键比如10个'x'则用"{x10}"来表示

实例1:
On Error Resume Next
Dim WshShell

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "notepad"
WScript.Sleep 2000
WshShell.AppActive "无标题 - 记事本"
WshShell.SendKeys "Hello, world! from VBScript"

实例2:
' Alt + F4是关机
On Error Resume Next
Dim wshShell, fs

Set fs = wscript.CreateObject("scripting.filesystemobject")
Set wshShell = wscript.CreateObject("wscript.Shell")

wshShell.Run "notepad"
wscript.sleep 1000
wshShell.AppAvtive "无标题 - 记事本"
wshShell.SendKeys "This is the most wonderful day of my life" & vbCrlf
wshShell.SendKeys "because I'm here with you now"
wscript.sleep 500
wshShell.SendKeys "%{F4}"
wscript.sleep 500
wshShell.SendKeys "s"
wscript.sleep 500
wshShell.SendKeys "a.txt"
wscript.sleep 500
wshShell.SendKeys "{ENTER}"

实例3: 简单QQ刷屏器
On Error Resume Next
Dim WshShell

Set WshShell = wscript.CreateObject("wscript.Shell")
WshShell.AppActive "电路飞翔A"
' Alt + s 为QQ的发送按键
For i = 1 To 5
    WScript.Sleep 500
    WshShell.SendKeys "^v"
    WshShell.SendKeys i
    WshShell.SendKeys "%s"
Next

 

实例4: 创文文本并写入自动保存

On Error Resume Next
Dim WshShell, AutoSaveTime, TXTFileName

Set WshShell = wscript.CreateObject("wscript.shell")
TEXTFileName = InputBox("请输入你要创建的文件名: ")

WshShell.Run "notepad"
Wscript.Sleep 200
'wscript.AppActive "无标题 - 记事本"

WshShell.SendKeys "Hello, this is created by vbs"
WshShell.SendKeys "^s"
Wscript.Sleep 300
WshShell.SendKeys TEXTFileName
Wscript.Sleep 1000
WshShell.SendKeys "%s"
WshShell.SendKeys "%"
WshShell.SendKeys "{ENTER}"
WshShell.SendKeys "x"

g) 关于FSO对象的详细操作

Windows中的文件属性一般用数字表示:

0表示普通文件,1表示只读文件,2表示隐藏文件,4表示系统文件

16表示文件夹或目录,32代表存档文件,1024代表链接或快捷方式

实例1: 获取文件属性

On Error Resume Next
Dim fs

Set fs = wscript.CreateObject("scripting.filesystemobject")
Set f = fs.getfile("C:\Users\Administrator\Desktop\a.txt")
MsgBox f.Attributes

实例2: 基于文件存在性创建文件

Dim fso
Set fso = wscript.CreateObject("scripting.filesystemobject")
If fso.fileexists("C:\Users\Administrator\Desktop\a.txt") Then
    MsgBox "文件已存在"
Else
    Set f = fso.createtextfile("C:\Users\Administrator\Desktop\a.txt", True) ' true代表强制覆盖
End If

实例3:

On Error Resume Next

Set fso = wscript.CreateObject("scripting.filesystemobject")
If fso.fileexists("C:\\Users\\Administrator\\Desktop\\a.txt") = False Then
    fso.createtextfile("C:\\Users\\Administrator\\Desktop\\a.txt")
Else
    wscript.echo "文件已存在"
End If
fso.copyfile "C:\\Users\\Administrator\\Desktop\\a.txt", "D:\\a.txt", True
fso.movefile "C:\\Users\\Administrator\\Desktop\\a.txt", "F:\\a.txt" ' 这个movefile可以跨盘
fso.deletefile "C:\\Users\\Administrator\\Desktop\\a.txt"

实例4:

On Error Resume Next

Dim fso, WshShell

Set fso = wscript.CreateObject("scripting.filesystemobject")
Set WshShell = wscript.CreateObject("wscript.shell")

WshShell.Run "notepad"

wscript.Sleep 1000
'wscript.AppActive "无标题 - 记事本"
WshShell.SendKeys "Hello, world! Here is from VBScript" & vbCrlf & "No, I dont like you"
WshShell.SendKeys "^s"
wscript.Sleep 2000
WshShell.SendKeys "a.txt"

WshShell.SendKeys "{ENTER}"
WshShell.SendKeys "%"
WshShell.SendKeys "{ENTER}"
WshShell.SendKeys "x"

wscript.Sleep 2000
Set ts = fso.opentextfile("C:\\Users\\Administrator\\Desktop\\a.txt", 1, True)
value = ts.read(20)
line = ts.readline
contents = ts.readall
MsgBox value & vbCrlf & line & vbCrlf & contents

实例5: 手动创建txt文件并写入一段话后

On Error Resume Next

Dim fso, WshShell

Set fso = wscript.CreateObject("scripting.filesystemobject")
Set WshShell = wscript.CreateObject("wscript.shell")

WshShell.Run "notepad"

wscript.Sleep 1000
'wscript.AppActive "无标题 - 记事本"
WshShell.SendKeys "Hello, world! Here is from VBScript" & vbCrlf & "No, I dont like you"
WshShell.SendKeys "^s"
wscript.Sleep 2000
WshShell.SendKeys "a.txt"

WshShell.SendKeys "{ENTER}"
WshShell.SendKeys "%"
WshShell.SendKeys "{ENTER}"
WshShell.SendKeys "x"

wscript.Sleep 2000


' 第二参数: 1表示只读,2表示写入,8为追加
' 第三参数: True表示不存在则创建

Set ts = fso.opentextfile("C:\\Users\\Administrator\\Desktop\\a.txt", 1, True)
value = ts.read(20)
line = ts.readline
contents = ts.readall
MsgBox value & vbCrlf & line & vbCrlf & contents

h) 文件指针的3个属性:

1. atendofstream属性,处于文件末尾该属性返回true

     do while fs.atendofstream <> true fs.read(10) loop

2. atendofline属性,处于行末尾返回true

3. Column和line属性,文件打开后都被设为1

4. skip(x) x表示跳过的字符 skipline跳过一行

5. 在文件中写入2和追加写入8.write(x)写入x个字符,writeline(x)写入第x行,

writeblanklines(n)写入n个空行

7. 最后一定要用close关闭。写入是独占的

D. 使用系统对话框

a) 系统对话框的对象及方法

1. SAFRCFileDlg.FileSave对象:

        FileName属性: 指定默认文件名

        FileType属性: 指定文件拓展名

        OpenFileSaveDlg方法: 显示文件保存框体的方法

2) SAFRCFileDlg.FileOpen对象:

        FileName属性: 同上

        OpenFileOpenDlg属性: 显示打开文件框体方法

3) UserAccounts.CommonDialog对象:

        FilterIndex属性,Filter拓展名属性,InitialDir属性: 指定默认文件夹

        FileName属性: 指定文件名, Flags属性: 对话框类型

        Show open方法

不知道为什么,这里案例全部失败了??(最后更新)

E. WMI

(最后更新)

F. scripting.dictionary对象

属性列表:

  • CompareMode 设定或返回键的字符串比较
  • Count 只读,返回键/条目对的数量
  • Item(key) 设定或返回指定键的条目值
  • Key(key) 设定键值

方法列表:

  • Add(key, item) 增加键/条目于字典中
  • Exists(key) 确定指定键是否存在,存在填True否则False
  • Items()返回一个包含字典对象中所有条目的数组
  • keys()返回一个包含字典对象中所有键的数组
  • Remove(key)删除特定键
  • RemoveAll()删除所有键和条目对

实例1:

On Error Resume Next

Set sdict = CreateObject("scripting.dictionary")
sdict.add "a", "apple"
sdict.add "b", "banana"
sdict.add "c", "copy"

MsgBox "总共条目有: " & sdict.count & vbCrlf & sdict.Item("a") & vbCrlf & sdict.Item("b") & vbCrlf & sdict.Item("c")

sdict.item("a") = "Dad"
sdict.item("b") = "Mum"
sdict.item("c") = "Son"

MsgBox "总共条目有: " & sdict.count & vbCrlf & sdict.Item("a") & vbCrlf & sdict.Item("b") & vbCrlf & sdict.Item("c")

sdict.Key("a") = "Father"
sdict.Key("b") = "Mother"
sdict.Key("c") = "Son"

MsgBox "总共条目有: " & sdict.count & vbCrlf & sdict.Item("Father") & vbCrlf & sdict.Item("Mother") & vbCrlf & sdict.Item("Son")

For Each Key In sdict.keys
	If Exists(Key) Then 
		MsgBox "键名" & Key & "是" & "=" & sdict(key)
	Else
		MsgBox "键不存在!"
	End If 
Next
sdict.removeall()

G. VBS的内置函数

1. Abs函数: 返回绝对值

2. Array函数: 返回数组的变体

3. Asc函数: 返回字符串首字母的ANSI字符码

4. Atn函数: 返回数值的反正切

5. CBool函数: 返回已被转换为 Boole an 子类型的变体的表达式

6. CreateObject 函数:创建并返回对“自动”对象的引用

(未完)

H. 事件对象

On Error Resume Next

Set objIE = wscript.CreateObject("InternetExplorer.Application", "event_")
objIE.Visible = True
MsgBox "请关闭浏览器窗口看效果", vbSystemModal
Wscript.sleep 6000
MsgBox "现在已经正常关闭了"

Sub event_OnQuit() 
	MsgBox "您确定要关闭浏览器吗?", vbSystemModal
End Sub 

上面那段代码的事件驱动没有效果,IE浏览器没有打得开,我试图通过wscript.Shell对象的Run方法调用IE浏览器并关闭来试图获取子过程的msgbox信息但是失败了,目前不知是怎么回事。

I. 通过ADO接口访问数据库

(持续更新)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(各种脚本语言学习)