活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

VBScript计算机编程基础从入门到精通掌握脚本语言的核心技术与应用实例助你快速提升编程能力成为专业开发者

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-27 02:50:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

VBScript(Visual Basic Scripting Edition)是一种由微软开发的脚本语言,它是Visual Basic家族的轻量级成员。作为一种解释型脚本语言,VBScript在Windows环境中有着广泛的应用,特别是在系统管理、网页开发(特别是ASP技术)和自动化任务方面。本文将带你从零开始,逐步深入VBScript的世界,帮助你掌握这门脚本语言的核心技术,并通过丰富的应用实例提升你的编程能力,最终成为一名专业的VBScript开发者。

VBScript概述

VBScript是一种基于组件对象模型(COM)的脚本语言,它继承了Visual Basic的基本语法,但更为简洁和灵活。VBScript最初设计用于网页客户端脚本,但由于安全考虑,现代浏览器已不再支持它。然而,在Windows系统管理和服务器端开发(特别是ASP)领域,VBScript仍然扮演着重要角色。

VBScript的特点

• 简单易学:语法简洁,适合初学者入门
• 平台依赖:主要运行在Windows环境下
• 解释执行:无需编译,代码逐行执行
• 自动化能力强:适合系统管理和任务自动化
• 与COM集成:可以调用各种COM组件扩展功能

VBScript的应用场景

• Windows系统管理脚本
• ASP网页开发
• WSH(Windows Script Host)脚本
• HTML应用程序(HTA)
• 自动化测试脚本

VBScript开发环境搭建

开始VBScript编程之前,需要准备适当的开发环境。

必要工具

1. 文本编辑器:任何纯文本编辑器都可以,如Notepad++、VS Code等
2. Windows Script Host(WSH):Windows系统自带,无需额外安装
3. Internet Explorer(可选):用于客户端VBScript开发(已过时)

创建第一个VBScript程序

让我们创建一个简单的”Hello, World!“程序:
  1. ' 第一个VBScript程序
  2. MsgBox "Hello, World!"
复制代码

将上述代码保存为hello.vbs文件,然后双击运行,你将看到一个显示”Hello, World!“的消息框。

VBScript基础语法

注释

在VBScript中,有两种注释方式:
  1. ' 这是单行注释
  2. REM 这也是单行注释,但较少使用
  3. ' 多行注释
  4. ' 需要在每行前面
  5. ' 添加单引号
复制代码

变量与常量

VBScript使用Dim语句声明变量:
  1. Dim name
  2. Dim age, address, salary  ' 一次声明多个变量
复制代码

VBScript是弱类型语言,所有变量都是Variant类型,可以存储任何类型的数据。
  1. name = "John Doe"
  2. age = 30
  3. address = "123 Main Street"
  4. salary = 50000.50
复制代码

• 必须以字母开头
• 不能包含句点(.)
• 不能超过255个字符
• 在作用域内必须唯一

使用Const语句声明常量:
  1. Const PI = 3.14159
  2. Const COMPANY_NAME = "ABC Corporation"
复制代码

数据类型

尽管VBScript中所有变量都是Variant类型,但它可以包含不同种类的子类型:

类型转换函数

VBScript提供了一系列类型转换函数:
  1. Dim strNum, num
  2. strNum = "123"
  3. ' 转换为整数
  4. num = CInt(strNum)  ' num现在是整数123
  5. ' 转换为字符串
  6. Dim numToStr
  7. numToStr = CStr(num)  ' numToStr现在是字符串"123"
  8. ' 其他转换函数
  9. Dim d, b, dt
  10. d = CDbl("3.14")      ' 转换为双精度
  11. b = CBool(1)          ' 转换为布尔值True
  12. dt = CDate("2023-11-15")  ' 转换为日期
复制代码

运算符

VBScript支持多种运算符:
  1. Dim a, b, result
  2. a = 10
  3. b = 3
  4. result = a + b   ' 加法,结果为13
  5. result = a - b   ' 减法,结果为7
  6. result = a * b   ' 乘法,结果为30
  7. result = a / b   ' 除法,结果为3.333...
  8. result = a Mod b ' 取模,结果为1
  9. result = a ^ b   ' 指数,结果为1000
复制代码
  1. Dim x, y
  2. x = 10
  3. y = 20
  4. Dim isEqual, isNotEqual, isGreater, isLess
  5. isEqual = (x = y)      ' False
  6. isNotEqual = (x <> y)  ' True
  7. isGreater = (x > y)    ' False
  8. isLess = (x < y)       ' True
复制代码
  1. Dim p, q
  2. p = True
  3. q = False
  4. Dim andResult, orResult, notResult
  5. andResult = p And q    ' False
  6. orResult = p Or q      ' True
  7. notResult = Not p      ' False
复制代码
  1. Dim firstName, lastName, fullName
  2. firstName = "John"
  3. lastName = "Doe"
  4. ' 使用&运算符连接字符串
  5. fullName = firstName & " " & lastName  ' "John Doe"
  6. ' 使用+运算符也可以连接字符串,但不推荐
  7. fullName = firstName + " " + lastName   ' "John Doe"
复制代码

控制结构

控制结构允许你根据条件执行不同的代码块或重复执行代码。

条件语句
  1. Dim age
  2. age = 18
  3. If age < 18 Then
  4.     MsgBox "未成年人"
  5. ElseIf age >= 18 And age < 60 Then
  6.     MsgBox "成年人"
  7. Else
  8.     MsgBox "老年人"
  9. End If
复制代码

当需要根据多个可能的值执行不同操作时,Select Case语句比多个If…Then…Else语句更清晰:
  1. Dim dayOfWeek
  2. dayOfWeek = 3  ' 假设3代表星期三
  3. Select Case dayOfWeek
  4.     Case 1
  5.         MsgBox "星期一"
  6.     Case 2
  7.         MsgBox "星期二"
  8.     Case 3
  9.         MsgBox "星期三"
  10.     Case 4
  11.         MsgBox "星期四"
  12.     Case 5
  13.         MsgBox "星期五"
  14.     Case 6, 7  ' 可以使用逗号指定多个值
  15.         MsgBox "周末"
  16.     Case Else
  17.         MsgBox "无效的日期"
  18. End Select
复制代码

循环语句

用于已知次数的循环:
  1. Dim i
  2. For i = 1 To 10
  3.     MsgBox "这是第 " & i & " 次循环"
  4. Next
  5. ' 使用Step关键字指定步长
  6. For i = 10 To 1 Step -1
  7.     MsgBox "倒计时: " & i
  8. Next
复制代码

用于遍历集合或数组中的每个元素:
  1. Dim fruits, fruit
  2. fruits = Array("Apple", "Banana", "Orange")
  3. For Each fruit In fruits
  4.     MsgBox "水果: " & fruit
  5. Next
复制代码

用于不确定循环次数的情况:
  1. Dim count
  2. count = 0
  3. ' Do While...Loop形式
  4. Do While count < 5
  5.     count = count + 1
  6.     MsgBox "计数: " & count
  7. Loop
  8. ' Do Until...Loop形式
  9. count = 0
  10. Do Until count >= 5
  11.     count = count + 1
  12.     MsgBox "计数: " & count
  13. Loop
  14. ' Do...Loop While形式
  15. count = 0
  16. Do
  17.     count = count + 1
  18.     MsgBox "计数: " & count
  19. Loop While count < 5
  20. ' Do...Loop Until形式
  21. count = 0
  22. Do
  23.     count = count + 1
  24.     MsgBox "计数: " & count
  25. Loop Until count >= 5
复制代码

这是VBScript中较老的循环结构,现在推荐使用Do…Loop:
  1. Dim count
  2. count = 0
  3. While count < 5
  4.     count = count + 1
  5.     MsgBox "计数: " & count
  6. Wend
复制代码

退出循环

使用Exit For或Exit Do可以提前退出循环:
  1. Dim i
  2. For i = 1 To 10
  3.     If i = 5 Then
  4.         Exit For  ' 当i等于5时退出循环
  5.     End If
  6.     MsgBox "i = " & i
  7. Next
  8. Dim count
  9. count = 0
  10. Do While count < 10
  11.     count = count + 1
  12.     If count = 5 Then
  13.         Exit Do  ' 当count等于5时退出循环
  14.     End If
  15.     MsgBox "count = " & count
  16. Loop
复制代码

过程与函数

VBScript允许你将代码组织为可重用的过程和函数。

Sub过程

Sub过程是执行一系列操作但不返回值的代码块:
  1. ' 定义一个Sub过程
  2. Sub ShowMessage(message)
  3.     MsgBox message
  4. End Sub
  5. ' 调用Sub过程
  6. ShowMessage "Hello from Sub procedure!"
复制代码

Function函数

Function函数执行操作并返回一个值:
  1. ' 定义一个Function函数
  2. Function AddNumbers(a, b)
  3.     AddNumbers = a + b  ' 使用函数名返回值
  4. End Function
  5. ' 调用Function函数
  6. Dim result
  7. result = AddNumbers(5, 3)
  8. MsgBox "5 + 3 = " & result  ' 显示 "5 + 3 = 8"
复制代码

参数传递

VBScript支持两种参数传递方式:ByVal(按值传递)和ByRef(按引用传递):
  1. ' ByVal示例
  2. Sub ByValExample(ByVal x)
  3.     x = x + 10
  4.     MsgBox "过程内的x值: " & x
  5. End Sub
  6. ' ByRef示例
  7. Sub ByRefExample(ByRef x)
  8.     x = x + 10
  9.     MsgBox "过程内的x值: " & x
  10. End Sub
  11. Dim num
  12. num = 5
  13. MsgBox "调用ByValExample前的num值: " & num  ' 显示5
  14. ByValExample num
  15. MsgBox "调用ByValExample后的num值: " & num  ' 仍显示5,因为按值传递不影响原变量
  16. MsgBox "调用ByRefExample前的num值: " & num  ' 显示5
  17. ByRefExample num
  18. MsgBox "调用ByRefExample后的num值: " & num  ' 显示15,因为按引用传递修改了原变量
复制代码

可选参数

VBScript支持可选参数,使用Optional关键字:
  1. Sub Greet(name, Optional greeting = "Hello")
  2.     MsgBox greeting & ", " & name & "!"
  3. End Sub
  4. Greet "John"           ' 显示 "Hello, John!"
  5. Greet "Jane", "Hi"     ' 显示 "Hi, Jane!"
复制代码

参数数组

使用ParamArray关键字可以接受可变数量的参数:
  1. Function Sum(ParamArray numbers())
  2.     Dim total, i
  3.     total = 0
  4.    
  5.     For i = LBound(numbers) To UBound(numbers)
  6.         total = total + numbers(i)
  7.     Next
  8.    
  9.     Sum = total
  10. End Function
  11. MsgBox "1 + 2 + 3 = " & Sum(1, 2, 3)           ' 显示 "1 + 2 + 3 = 6"
  12. MsgBox "1 + 2 + 3 + 4 + 5 = " & Sum(1, 2, 3, 4, 5)  ' 显示 "1 + 2 + 3 + 4 + 5 = 15"
复制代码

数组

数组是存储多个相同类型值的变量集合。

声明数组
  1. ' 声明固定大小的数组
  2. Dim fruits(2)  ' 创建一个包含3个元素的数组(索引0、1、2)
  3. fruits(0) = "Apple"
  4. fruits(1) = "Banana"
  5. fruits(2) = "Orange"
  6. ' 声明动态数组
  7. Dim dynamicArray()
  8. ReDim dynamicArray(2)  ' 初始大小为3
  9. dynamicArray(0) = "A"
  10. dynamicArray(1) = "B"
  11. dynamicArray(2) = "C"
  12. ' 使用Preserve关键字调整数组大小并保留现有值
  13. ReDim Preserve dynamicArray(4)  ' 现在大小为5,保留原有值
  14. dynamicArray(3) = "D"
  15. dynamicArray(4) = "E"
复制代码

多维数组
  1. ' 声明二维数组
  2. Dim matrix(2, 2)  ' 3x3的矩阵
  3. matrix(0, 0) = 1
  4. matrix(0, 1) = 2
  5. matrix(0, 2) = 3
  6. matrix(1, 0) = 4
  7. matrix(1, 1) = 5
  8. matrix(1, 2) = 6
  9. matrix(2, 0) = 7
  10. matrix(2, 1) = 8
  11. matrix(2, 2) = 9
复制代码

数组函数

VBScript提供了一些内置函数来处理数组:
  1. Dim arr, i
  2. ' Array函数创建数组
  3. arr = Array("A", "B", "C", "D", "E")
  4. ' LBound和UBound函数获取数组的下界和上界
  5. MsgBox "数组下界: " & LBound(arr)  ' 显示0
  6. MsgBox "数组上界: " & UBound(arr)  ' 显示4
  7. ' 遍历数组
  8. For i = LBound(arr) To UBound(arr)
  9.     MsgBox "arr(" & i & ") = " & arr(i)
  10. Next
  11. ' Join函数将数组连接为字符串
  12. Dim str
  13. str = Join(arr, ", ")
  14. MsgBox "连接后的字符串: " & str  ' 显示 "A, B, C, D, E"
  15. ' Split函数将字符串分割为数组
  16. Dim sentence, words
  17. sentence = "This is a sample sentence"
  18. words = Split(sentence, " ")
  19. MsgBox "分割后的单词数量: " & UBound(words) + 1  ' 显示5
复制代码

动态数组操作
  1. ' 动态添加元素到数组
  2. Function AddToArray(arr, element)
  3.     Dim newSize
  4.     newSize = UBound(arr) + 1
  5.     ReDim Preserve arr(newSize)
  6.     arr(newSize) = element
  7.     AddToArray = arr
  8. End Function
  9. Dim myArray
  10. myArray = Array("A", "B", "C")
  11. myArray = AddToArray(myArray, "D")
  12. ' 动态从数组中删除元素
  13. Function RemoveFromArray(arr, index)
  14.     Dim i
  15.     For i = index To UBound(arr) - 1
  16.         arr(i) = arr(i + 1)
  17.     Next
  18.     ReDim Preserve arr(UBound(arr) - 1)
  19.     RemoveFromArray = arr
  20. End Function
  21. myArray = RemoveFromArray(myArray, 1)  ' 删除索引1处的元素"B"
复制代码

错误处理

良好的错误处理是编写健壮脚本的关键。

On Error语句
  1. ' 基本错误处理
  2. On Error Resume Next  ' 发生错误时继续执行下一行代码
  3. Dim result
  4. result = 10 / 0  ' 这会导致除以零错误
  5. If Err.Number <> 0 Then
  6.     MsgBox "发生错误: " & Err.Description
  7.     Err.Clear  ' 清除错误对象
  8. End If
  9. On Error GoTo 0  ' 关闭错误处理
复制代码

结构化错误处理

虽然VBScript没有像其他语言那样的try…catch结构,但可以通过子程序模拟:
  1. Sub SafeDivision(a, b)
  2.     On Error Resume Next
  3.    
  4.     Dim result
  5.     result = a / b
  6.    
  7.     If Err.Number <> 0 Then
  8.         MsgBox "除法错误: " & Err.Description
  9.         Err.Clear
  10.     Else
  11.         MsgBox a & " / " & b & " = " & result
  12.     End If
  13.    
  14.     On Error GoTo 0
  15. End Sub
  16. SafeDivision 10, 2   ' 正常执行
  17. SafeDivision 10, 0   ' 显示错误信息
复制代码

自定义错误

你可以使用Err对象的Raise方法生成自定义错误:
  1. Sub ValidateAge(age)
  2.     If age < 0 Then
  3.         Err.Raise vbObjectError + 1, "ValidateAge", "年龄不能为负数"
  4.     ElseIf age > 150 Then
  5.         Err.Raise vbObjectError + 2, "ValidateAge", "年龄不能超过150岁"
  6.     End If
  7. End Sub
  8. On Error Resume Next
  9. ValidateAge -5
  10. If Err.Number <> 0 Then
  11.     MsgBox "错误 #" & Err.Number & ": " & Err.Description
  12.     Err.Clear
  13. End If
  14. On Error GoTo 0
复制代码

文件系统操作

VBScript可以通过FileSystemObject对象进行文件系统操作。

创建FileSystemObject
  1. Dim fso
  2. Set fso = CreateObject("Scripting.FileSystemObject")
复制代码

文件操作
  1. Dim fso, file
  2. Set fso = CreateObject("Scripting.FileSystemObject")
  3. ' 创建文本文件并写入内容
  4. Set file = fso.CreateTextFile("C:\Temp\test.txt", True)  ' True表示覆盖已存在的文件
  5. file.WriteLine "这是第一行"
  6. file.WriteLine "这是第二行"
  7. file.Write "这是第三行,没有换行"
  8. file.Close
  9. ' 追加内容到文件
  10. If fso.FileExists("C:\Temp\test.txt") Then
  11.     Set file = fso.OpenTextFile("C:\Temp\test.txt", 8)  ' 8表示追加模式
  12.     file.WriteLine vbCrLf & "这是追加的内容"
  13.     file.Close
  14. End If
复制代码
  1. Dim fso, file, content
  2. Set fso = CreateObject("Scripting.FileSystemObject")
  3. ' 检查文件是否存在
  4. If fso.FileExists("C:\Temp\test.txt") Then
  5.     ' 读取整个文件
  6.     Set file = fso.OpenTextFile("C:\Temp\test.txt", 1)  ' 1表示只读模式
  7.     content = file.ReadAll
  8.     file.Close
  9.     MsgBox "文件内容:" & vbCrLf & content
  10.    
  11.     ' 逐行读取文件
  12.     Set file = fso.OpenTextFile("C:\Temp\test.txt", 1)
  13.     content = ""
  14.     Do Until file.AtEndOfStream
  15.         content = content & file.ReadLine & vbCrLf
  16.     Loop
  17.     file.Close
  18.     MsgBox "逐行读取的文件内容:" & vbCrLf & content
  19. End If
复制代码
  1. Dim fso
  2. Set fso = CreateObject("Scripting.FileSystemObject")
  3. ' 创建文件夹
  4. If Not fso.FolderExists("C:\Temp\TestFolder") Then
  5.     fso.CreateFolder "C:\Temp\TestFolder"
  6.     MsgBox "文件夹已创建"
  7. End If
  8. ' 复制文件
  9. If fso.FileExists("C:\Temp\test.txt") Then
  10.     fso.CopyFile "C:\Temp\test.txt", "C:\Temp\TestFolder\test_copy.txt"
  11.     MsgBox "文件已复制"
  12. End If
  13. ' 移动文件
  14. If fso.FileExists("C:\Temp\TestFolder\test_copy.txt") Then
  15.     fso.MoveFile "C:\Temp\TestFolder\test_copy.txt", "C:\Temp\TestFolder\test_moved.txt"
  16.     MsgBox "文件已移动"
  17. End If
  18. ' 删除文件
  19. If fso.FileExists("C:\Temp\TestFolder\test_moved.txt") Then
  20.     fso.DeleteFile "C:\Temp\TestFolder\test_moved.txt"
  21.     MsgBox "文件已删除"
  22. End If
  23. ' 删除文件夹
  24. If fso.FolderExists("C:\Temp\TestFolder") Then
  25.     fso.DeleteFolder "C:\Temp\TestFolder"
  26.     MsgBox "文件夹已删除"
  27. End If
复制代码
  1. Dim fso, file, folder, fileInfo
  2. Set fso = CreateObject("Scripting.FileSystemObject")
  3. ' 获取文件信息
  4. If fso.FileExists("C:\Temp\test.txt") Then
  5.     Set file = fso.GetFile("C:\Temp\test.txt")
  6.     fileInfo = "文件名: " & file.Name & vbCrLf
  7.     fileInfo = fileInfo & "路径: " & file.Path & vbCrLf
  8.     fileInfo = fileInfo & "大小: " & file.Size & " 字节" & vbCrLf
  9.     fileInfo = fileInfo & "创建日期: " & file.DateCreated & vbCrLf
  10.     fileInfo = fileInfo & "最后修改日期: " & file.DateLastModified & vbCrLf
  11.     fileInfo = fileInfo & "最后访问日期: " & file.DateLastAccessed
  12.     MsgBox fileInfo
  13. End If
  14. ' 获取文件夹信息
  15. If fso.FolderExists("C:\Temp") Then
  16.     Set folder = fso.GetFolder("C:\Temp")
  17.     fileInfo = "文件夹名: " & folder.Name & vbCrLf
  18.     fileInfo = fileInfo & "路径: " & folder.Path & vbCrLf
  19.     fileInfo = fileInfo & "大小: " & folder.Size & " 字节" & vbCrLf
  20.     fileInfo = fileInfo & "创建日期: " & folder.DateCreated & vbCrLf
  21.     fileInfo = fileInfo & "包含文件数: " & folder.Files.Count & vbCrLf
  22.     fileInfo = fileInfo & "包含子文件夹数: " & folder.SubFolders.Count
  23.     MsgBox fileInfo
  24. End If
复制代码
  1. Dim fso, folder, file, subfolder, fileList
  2. Set fso = CreateObject("Scripting.FileSystemObject")
  3. ' 遍历文件夹中的文件
  4. If fso.FolderExists("C:\Temp") Then
  5.     Set folder = fso.GetFolder("C:\Temp")
  6.     fileList = "文件夹 " & folder.Path & " 中的文件:" & vbCrLf & vbCrLf
  7.    
  8.     For Each file In folder.Files
  9.         fileList = fileList & file.Name & " (" & file.Size & " 字节)" & vbCrLf
  10.     Next
  11.    
  12.     MsgBox fileList
  13. End If
  14. ' 递归遍历所有子文件夹
  15. Sub ListAllFolders(folderPath)
  16.     Dim fso, folder, subfolder, file
  17.     Set fso = CreateObject("Scripting.FileSystemObject")
  18.    
  19.     If fso.FolderExists(folderPath) Then
  20.         Set folder = fso.GetFolder(folderPath)
  21.         
  22.         ' 列出当前文件夹中的文件
  23.         For Each file In folder.Files
  24.             WScript.Echo folderPath & "" & file.Name
  25.         Next
  26.         
  27.         ' 递归处理子文件夹
  28.         For Each subfolder In folder.SubFolders
  29.             ListAllFolders subfolder.Path
  30.         Next
  31.     End If
  32. End Sub
  33. ' 调用递归函数
  34. ListAllFolders "C:\Temp"
复制代码

Windows系统交互

VBScript可以与Windows系统进行深度交互,执行各种管理任务。

WScript和CScript

VBScript可以通过WSH(Windows Script Host)运行,有两种宿主程序:

• WScript.exe:Windows应用程序,用于图形界面环境
• CScript.exe:控制台应用程序,用于命令行环境
  1. ' 检测当前运行的宿主程序
  2. If InStr(1, WScript.FullName, "cscript.exe", vbTextCompare) > 0 Then
  3.     WScript.Echo "运行在CScript下"
  4. Else
  5.     MsgBox "运行在WScript下"
  6. End If
复制代码

系统信息获取
  1. ' 获取计算机名和用户名
  2. Dim wshNetwork
  3. Set wshNetwork = CreateObject("WScript.Network")
  4. MsgBox "计算机名: " & wshNetwork.ComputerName & vbCrLf & _
  5.        "用户名: " & wshNetwork.UserName & vbCrLf & _
  6.        "用户域: " & wshNetwork.UserDomain
  7. ' 获取环境变量
  8. Dim wshShell
  9. Set wshShell = CreateObject("WScript.Shell")
  10. MsgBox "系统目录: " & wshShell.ExpandEnvironmentStrings("%WINDIR%") & vbCrLf & _
  11.        "临时目录: " & wshShell.ExpandEnvironmentStrings("%TEMP%") & vbCrLf & _
  12.        "程序文件目录: " & wshShell.ExpandEnvironmentStrings("%ProgramFiles%")
复制代码

注册表操作
  1. Dim wshShell
  2. Set wshShell = CreateObject("WScript.Shell")
  3. ' 读取注册表值
  4. On Error Resume Next
  5. Dim ieVersion
  6. ieVersion = wshShell.RegRead("HKLM\SOFTWARE\Microsoft\Internet Explorer\Version")
  7. If Err.Number <> 0 Then
  8.     MsgBox "无法读取IE版本: " & Err.Description
  9.     Err.Clear
  10. Else
  11.     MsgBox "Internet Explorer版本: " & ieVersion
  12. End If
  13. ' 写入注册表值
  14. ' 注意:写入注册表需要管理员权限
  15. wshShell.RegWrite "HKCU\Software\MyApp\Setting1", "Test Value", "REG_SZ"
  16. wshShell.RegWrite "HKCU\Software\MyApp\Setting2", 123, "REG_DWORD"
  17. ' 删除注册表值
  18. wshShell.RegDelete "HKCU\Software\MyApp\Setting1"
  19. wshShell.RegDelete "HKCU\Software\MyApp\Setting2"
  20. wshShell.RegDelete "HKCU\Software\MyApp"  ' 删除整个键
复制代码

进程管理
  1. Dim wshShell
  2. Set wshShell = CreateObject("WScript.Shell")
  3. ' 启动应用程序
  4. wshShell.Run "notepad.exe"  ' 启动记事本
  5. wshShell.Run "calc.exe"     ' 启动计算器
  6. ' 等待应用程序结束
  7. wshShell.Run "notepad.exe", 1, True  ' 1表示正常窗口,True表示等待结束
  8. MsgBox "记事本已关闭"
  9. ' 终止进程
  10. Dim processes
  11. Set processes = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process Where Name='notepad.exe'")
  12. For Each process In processes
  13.     process.Terminate()
  14. Next
复制代码

系统服务管理
  1. ' 列出所有服务
  2. Dim services
  3. Set services = GetObject("winmgmts:").ExecQuery("Select * from Win32_Service")
  4. Dim serviceList
  5. serviceList = "系统服务列表:" & vbCrLf & vbCrLf
  6. For Each service In services
  7.     serviceList = serviceList & service.Name & " - " & service.State & vbCrLf
  8. Next
  9. ' 由于服务列表可能很长,这里只显示前10个
  10. MsgBox Left(serviceList, 1000) & "..."
  11. ' 检查特定服务状态
  12. Dim specificService
  13. Set specificService = GetObject("winmgmts:").ExecQuery("Select * from Win32_Service Where Name='Winmgmt'")
  14. For Each service In specificService
  15.     MsgBox "Windows Management Instrumentation 服务状态: " & service.State & vbCrLf & _
  16.            "启动类型: " & service.StartMode & vbCrLf & _
  17.            "显示名称: " & service.DisplayName
  18. Next
复制代码

事件日志操作
  1. ' 读取应用程序事件日志
  2. Dim wmi, eventLogs, eventLog
  3. Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
  4. Set eventLogs = wmi.ExecQuery("Select * from Win32_NTLogEvent Where Logfile='Application'")
  5. Dim logEntry, count
  6. count = 0
  7. logEntry = "最近的应用程序事件日志条目:" & vbCrLf & vbCrLf
  8. For Each eventLog In eventLogs
  9.     count = count + 1
  10.     logEntry = logEntry & "时间: " & eventLog.TimeGenerated & vbCrLf
  11.     logEntry = logEntry & "类型: " & eventLog.Type & vbCrLf
  12.     logEntry = logEntry & "来源: " & eventLog.SourceName & vbCrLf
  13.     logEntry = logEntry & "事件ID: " & eventLog.EventCode & vbCrLf
  14.     logEntry = logEntry & "消息: " & Left(eventLog.Message, 100) & "..." & vbCrLf
  15.     logEntry = logEntry & "--------------------------------" & vbCrLf
  16.    
  17.     If count >= 5 Then Exit For  ' 只显示前5条
  18. Next
  19. MsgBox logEntry
  20. ' 写入自定义事件日志
  21. Dim wshShell
  22. Set wshShell = CreateObject("WScript.Shell")
  23. wshShell.LogEvent 4, "这是一个由VBScript写入的信息事件"  ' 4表示信息事件
  24. wshShell.LogEvent 2, "这是一个由VBScript写入的错误事件"  ' 2表示错误事件
  25. wshShell.LogEvent 1, "这是一个由VBScript写入的警告事件"  ' 1表示警告事件
复制代码

网络操作

VBScript可以执行各种网络相关操作,如网络配置检查、网络通信等。

网络配置检查
  1. ' 获取网络适配器信息
  2. Dim wmi, adapters, adapter
  3. Set wmi = GetObject("winmgmts:\\.\root\cimv2")
  4. Set adapters = wmi.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
  5. Dim adapterInfo
  6. adapterInfo = "网络适配器信息:" & vbCrLf & vbCrLf
  7. For Each adapter In adapters
  8.     adapterInfo = adapterInfo & "描述: " & adapter.Description & vbCrLf
  9.     adapterInfo = adapterInfo & "MAC地址: " & adapter.MACAddress & vbCrLf
  10.    
  11.     If Not IsNull(adapter.IPAddress) Then
  12.         adapterInfo = adapterInfo & "IP地址: " & Join(adapter.IPAddress, ", ") & vbCrLf
  13.     End If
  14.    
  15.     If Not IsNull(adapter.IPSubnet) Then
  16.         adapterInfo = adapterInfo & "子网掩码: " & Join(adapter.IPSubnet, ", ") & vbCrLf
  17.     End If
  18.    
  19.     If Not IsNull(adapter.DefaultIPGateway) Then
  20.         adapterInfo = adapterInfo & "默认网关: " & Join(adapter.DefaultIPGateway, ", ") & vbCrLf
  21.     End If
  22.    
  23.     If Not IsNull(adapter.DNSServerSearchOrder) Then
  24.         adapterInfo = adapterInfo & "DNS服务器: " & Join(adapter.DNSServerSearchOrder, ", ") & vbCrLf
  25.     End If
  26.    
  27.     adapterInfo = adapterInfo & "DHCP启用: " & adapter.DHCPEnabled & vbCrLf
  28.    
  29.     If adapter.DHCPEnabled Then
  30.         adapterInfo = adapterInfo & "DHCP服务器: " & adapter.DHCPServer & vbCrLf
  31.         adapterInfo = adapterInfo & "DHCP租约获取时间: " & adapter.DHCPLeaseObtained & vbCrLf
  32.         adapterInfo = adapterInfo & "DHCP租约过期时间: " & adapter.DHCPLeaseExpires & vbCrLf
  33.     End If
  34.    
  35.     adapterInfo = adapterInfo & "--------------------------------" & vbCrLf
  36. Next
  37. MsgBox adapterInfo
复制代码

网络连通性测试
  1. ' Ping测试
  2. Function Ping(host)
  3.     Dim wshShell, cmd, exec, output, lines, i
  4.     Set wshShell = CreateObject("WScript.Shell")
  5.    
  6.     cmd = "%comspec% /c ping -n 1 -w 1000 " & host
  7.     Set exec = wshShell.Exec(cmd)
  8.    
  9.     Do While exec.Status = 0
  10.         WScript.Sleep 100
  11.     Loop
  12.    
  13.     output = exec.StdOut.ReadAll()
  14.    
  15.     If InStr(output, "TTL=") > 0 Then
  16.         Ping = True
  17.     Else
  18.         Ping = False
  19.     End If
  20. End Function
  21. ' 测试网络连通性
  22. Dim hosts, host, result
  23. hosts = Array("127.0.0.1", "www.google.com", "www.microsoft.com")
  24. result = "网络连通性测试结果:" & vbCrLf & vbCrLf
  25. For Each host In hosts
  26.     If Ping(host) Then
  27.         result = result & host & " - 可达" & vbCrLf
  28.     Else
  29.         result = result & host & " - 不可达" & vbCrLf
  30.     End If
  31. Next
  32. MsgBox result
复制代码

网络共享操作
  1. ' 列出网络共享
  2. Dim wmi, shares, share
  3. Set wmi = GetObject("winmgmts:\\.\root\cimv2")
  4. Set shares = wmi.ExecQuery("Select * from Win32_Share")
  5. Dim shareList
  6. shareList = "网络共享列表:" & vbCrLf & vbCrLf
  7. For Each share In shares
  8.     shareList = shareList & "名称: " & share.Name & vbCrLf
  9.     shareList = shareList & "路径: " & share.Path & vbCrLf
  10.     shareList = shareList & "描述: " & share.Description & vbCrLf
  11.     shareList = shareList & "类型: " & share.Type & vbCrLf
  12.     shareList = shareList & "--------------------------------" & vbCrLf
  13. Next
  14. MsgBox shareList
  15. ' 映射网络驱动器
  16. Dim wshNetwork
  17. Set wshNetwork = CreateObject("WScript.Network")
  18. On Error Resume Next
  19. ' 映射网络驱动器Z:到\\server\share
  20. wshNetwork.MapNetworkDrive "Z:", "\\server\share"
  21. If Err.Number <> 0 Then
  22.     MsgBox "映射网络驱动器失败: " & Err.Description
  23.     Err.Clear
  24. Else
  25.     MsgBox "网络驱动器Z:已成功映射"
  26. End If
  27. ' 断开网络驱动器
  28. wshNetwork.RemoveNetworkDrive "Z:"
  29. If Err.Number <> 0 Then
  30.     MsgBox "断开网络驱动器失败: " & Err.Description
  31.     Err.Clear
  32. Else
  33.     MsgBox "网络驱动器Z:已成功断开"
  34. End If
  35. On Error GoTo 0
复制代码

数据库操作

VBScript可以通过ADO(ActiveX Data Objects)连接和操作数据库。

连接数据库
  1. ' 连接到Access数据库
  2. Sub ConnectToAccess()
  3.     Dim conn, connStr
  4.    
  5.     ' 创建连接对象
  6.     Set conn = CreateObject("ADODB.Connection")
  7.    
  8.     ' 连接字符串
  9.     connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\MyDatabase.accdb;"
  10.    
  11.     ' 打开连接
  12.     conn.Open connStr
  13.    
  14.     MsgBox "成功连接到Access数据库"
  15.    
  16.     ' 关闭连接
  17.     conn.Close
  18.     Set conn = Nothing
  19. End Sub
  20. ' 连接到SQL Server数据库
  21. Sub ConnectToSQLServer()
  22.     Dim conn, connStr
  23.    
  24.     ' 创建连接对象
  25.     Set conn = CreateObject("ADODB.Connection")
  26.    
  27.     ' 连接字符串
  28.     connStr = "Provider=SQLOLEDB;Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;User ID=USERNAME;Password=PASSWORD;"
  29.    
  30.     ' 打开连接
  31.     conn.Open connStr
  32.    
  33.     MsgBox "成功连接到SQL Server数据库"
  34.    
  35.     ' 关闭连接
  36.     conn.Close
  37.     Set conn = Nothing
  38. End Sub
复制代码

执行SQL查询
  1. ' 执行查询并获取结果
  2. Sub ExecuteQuery()
  3.     Dim conn, connStr, rs, sql
  4.    
  5.     ' 创建连接对象
  6.     Set conn = CreateObject("ADODB.Connection")
  7.    
  8.     ' 连接字符串(以Access为例)
  9.     connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\MyDatabase.accdb;"
  10.    
  11.     ' 打开连接
  12.     conn.Open connStr
  13.    
  14.     ' 创建记录集对象
  15.     Set rs = CreateObject("ADODB.Recordset")
  16.    
  17.     ' SQL查询语句
  18.     sql = "SELECT * FROM Customers"
  19.    
  20.     ' 执行查询
  21.     rs.Open sql, conn
  22.    
  23.     ' 处理结果
  24.     Dim result
  25.     result = "查询结果:" & vbCrLf & vbCrLf
  26.    
  27.     ' 显示列名
  28.     Dim i
  29.     For i = 0 To rs.Fields.Count - 1
  30.         result = result & rs.Fields(i).Name & vbTab
  31.     Next
  32.     result = result & vbCrLf
  33.    
  34.     ' 显示数据
  35.     Do Until rs.EOF
  36.         For i = 0 To rs.Fields.Count - 1
  37.             result = result & rs.Fields(i).Value & vbTab
  38.         Next
  39.         result = result & vbCrLf
  40.         rs.MoveNext
  41.     Loop
  42.    
  43.     MsgBox result
  44.    
  45.     ' 关闭记录集和连接
  46.     rs.Close
  47.     conn.Close
  48.     Set rs = Nothing
  49.     Set conn = Nothing
  50. End Sub
复制代码

执行更新操作
  1. ' 执行插入、更新和删除操作
  2. Sub ExecuteUpdate()
  3.     Dim conn, connStr, sql
  4.    
  5.     ' 创建连接对象
  6.     Set conn = CreateObject("ADODB.Connection")
  7.    
  8.     ' 连接字符串(以Access为例)
  9.     connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\MyDatabase.accdb;"
  10.    
  11.     ' 打开连接
  12.     conn.Open connStr
  13.    
  14.     ' 插入记录
  15.     sql = "INSERT INTO Customers (CustomerName, ContactName, Country) VALUES ('Test Customer', 'John Doe', 'USA')"
  16.     conn.Execute sql
  17.     MsgBox "已插入新记录"
  18.    
  19.     ' 更新记录
  20.     sql = "UPDATE Customers SET ContactName = 'Jane Doe' WHERE CustomerName = 'Test Customer'"
  21.     conn.Execute sql
  22.     MsgBox "已更新记录"
  23.    
  24.     ' 删除记录
  25.     sql = "DELETE FROM Customers WHERE CustomerName = 'Test Customer'"
  26.     conn.Execute sql
  27.     MsgBox "已删除记录"
  28.    
  29.     ' 关闭连接
  30.     conn.Close
  31.     Set conn = Nothing
  32. End Sub
复制代码

使用参数化查询
  1. ' 使用参数化查询防止SQL注入
  2. Sub ParameterizedQuery()
  3.     Dim conn, connStr, cmd, param
  4.    
  5.     ' 创建连接对象
  6.     Set conn = CreateObject("ADODB.Connection")
  7.    
  8.     ' 连接字符串(以Access为例)
  9.     connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\MyDatabase.accdb;"
  10.    
  11.     ' 打开连接
  12.     conn.Open connStr
  13.    
  14.     ' 创建命令对象
  15.     Set cmd = CreateObject("ADODB.Command")
  16.     cmd.ActiveConnection = conn
  17.    
  18.     ' 设置SQL语句
  19.     cmd.CommandText = "SELECT * FROM Customers WHERE Country = ?"
  20.    
  21.     ' 创建参数
  22.     Set param = cmd.CreateParameter("Country", 200, 1, 50, "USA")  ' 200表示adVarChar,1表示adParamInput
  23.     cmd.Parameters.Append param
  24.    
  25.     ' 执行查询
  26.     Dim rs
  27.     Set rs = cmd.Execute
  28.    
  29.     ' 处理结果
  30.     Dim result
  31.     result = "查询结果:" & vbCrLf & vbCrLf
  32.    
  33.     ' 显示列名
  34.     Dim i
  35.     For i = 0 To rs.Fields.Count - 1
  36.         result = result & rs.Fields(i).Name & vbTab
  37.     Next
  38.     result = result & vbCrLf
  39.    
  40.     ' 显示数据
  41.     Do Until rs.EOF
  42.         For i = 0 To rs.Fields.Count - 1
  43.             result = result & rs.Fields(i).Value & vbTab
  44.         Next
  45.         result = result & vbCrLf
  46.         rs.MoveNext
  47.     Loop
  48.    
  49.     MsgBox result
  50.    
  51.     ' 关闭记录集和连接
  52.     rs.Close
  53.     conn.Close
  54.     Set rs = Nothing
  55.     Set cmd = Nothing
  56.     Set conn = Nothing
  57. End Sub
复制代码

实际应用案例

自动备份脚本
  1. ' 文件自动备份脚本
  2. Option Explicit
  3. ' 配置部分
  4. Const SOURCE_FOLDER = "C:\ImportantFiles"    ' 源文件夹
  5. Const BACKUP_FOLDER = "D:\Backups"            ' 备份文件夹
  6. Const LOG_FILE = "D:\Backups\backup_log.txt"  ' 日志文件
  7. ' 主程序
  8. Dim fso, startTime, endTime, duration
  9. Set fso = CreateObject("Scripting.FileSystemObject")
  10. startTime = Now
  11. ' 记录开始时间
  12. LogMessage "备份开始于: " & startTime
  13. ' 检查源文件夹是否存在
  14. If Not fso.FolderExists(SOURCE_FOLDER) Then
  15.     LogMessage "错误: 源文件夹 " & SOURCE_FOLDER & " 不存在!"
  16.     WScript.Quit 1
  17. End If
  18. ' 创建备份文件夹(如果不存在)
  19. If Not fso.FolderExists(BACKUP_FOLDER) Then
  20.     fso.CreateFolder BACKUP_FOLDER
  21.     LogMessage "创建备份文件夹: " & BACKUP_FOLDER
  22. End If
  23. ' 创建以日期命名的子文件夹
  24. Dim backupSubFolder
  25. backupSubFolder = BACKUP_FOLDER & "\Backup_" & Replace(FormatDateTime(Now, 2), "/", "-")
  26. If Not fso.FolderExists(backupSubFolder) Then
  27.     fso.CreateFolder backupSubFolder
  28.     LogMessage "创建备份子文件夹: " & backupSubFolder
  29. End If
  30. ' 执行备份
  31. CopyFolderContents SOURCE_FOLDER, backupSubFolder
  32. endTime = Now
  33. duration = DateDiff("n", startTime, endTime)
  34. LogMessage "备份完成于: " & endTime
  35. LogMessage "备份耗时: " & duration & " 分钟"
  36. MsgBox "备份完成! 耗时: " & duration & " 分钟", vbInformation, "备份完成"
  37. ' 子程序:复制文件夹内容
  38. Sub CopyFolderContents(sourceFolder, destFolder)
  39.     Dim folder, file, subfolder
  40.    
  41.     Set folder = fso.GetFolder(sourceFolder)
  42.    
  43.     ' 复制文件
  44.     For Each file In folder.Files
  45.         On Error Resume Next
  46.         fso.CopyFile file.Path, destFolder & "" & file.Name, True
  47.         
  48.         If Err.Number <> 0 Then
  49.             LogMessage "错误: 无法复制文件 " & file.Path & " - " & Err.Description
  50.             Err.Clear
  51.         Else
  52.             LogMessage "已复制文件: " & file.Name
  53.         End If
  54.         
  55.         On Error GoTo 0
  56.     Next
  57.    
  58.     ' 递归复制子文件夹
  59.     For Each subfolder In folder.SubFolders
  60.         Dim newDestFolder
  61.         newDestFolder = destFolder & "" & subfolder.Name
  62.         
  63.         If Not fso.FolderExists(newDestFolder) Then
  64.             fso.CreateFolder newDestFolder
  65.         End If
  66.         
  67.         CopyFolderContents subfolder.Path, newDestFolder
  68.     Next
  69. End Sub
  70. ' 子程序:记录日志
  71. Sub LogMessage(message)
  72.     Dim logFile
  73.    
  74.     On Error Resume Next
  75.     Set logFile = fso.OpenTextFile(LOG_FILE, 8, True)  ' 8表示追加模式
  76.    
  77.     If Err.Number <> 0 Then
  78.         MsgBox "无法写入日志文件: " & Err.Description, vbExclamation, "错误"
  79.         Exit Sub
  80.     End If
  81.    
  82.     logFile.WriteLine Now & " - " & message
  83.     logFile.Close
  84.    
  85.     On Error GoTo 0
  86. End Sub
复制代码

系统信息收集器
  1. ' 系统信息收集器
  2. Option Explicit
  3. ' 配置部分
  4. Const OUTPUT_FILE = "C:\Temp\SystemInfo.txt"  ' 输出文件
  5. ' 主程序
  6. Dim fso, outputFile, wshNetwork, wshShell, computerSystem, operatingSystem, processors
  7. Set fso = CreateObject("Scripting.FileSystemObject")
  8. Set wshNetwork = CreateObject("WScript.Network")
  9. Set wshShell = CreateObject("WScript.Shell")
  10. ' 创建输出文件
  11. Set outputFile = fso.CreateTextFile(OUTPUT_FILE, True)
  12. ' 写入标题
  13. outputFile.WriteLine "========================================"
  14. outputFile.WriteLine "          系统信息报告"
  15. outputFile.WriteLine "========================================"
  16. outputFile.WriteLine "生成时间: " & Now
  17. outputFile.WriteLine "========================================"
  18. outputFile.WriteLine ""
  19. ' 基本信息
  20. outputFile.WriteLine "【基本信息】"
  21. outputFile.WriteLine "计算机名: " & wshNetwork.ComputerName
  22. outputFile.WriteLine "用户名: " & wshNetwork.UserName
  23. outputFile.WriteLine "用户域: " & wshNetwork.UserDomain
  24. outputFile.WriteLine ""
  25. ' 操作系统信息
  26. outputFile.WriteLine "【操作系统信息】"
  27. Dim wmi, osItems, osItem
  28. Set wmi = GetObject("winmgmts:\\.\root\cimv2")
  29. Set osItems = wmi.ExecQuery("Select * from Win32_OperatingSystem")
  30. For Each osItem In osItems
  31.     outputFile.WriteLine "操作系统: " & osItem.Caption
  32.     outputFile.WriteLine "版本: " & osItem.Version
  33.     outputFile.WriteLine "服务包: " & osItem.ServicePackMajorVersion & "." & osItem.ServicePackMinorVersion
  34.     outputFile.WriteLine "安装日期: " & osItem.InstallDate
  35.     outputFile.WriteLine "上次启动时间: " & osItem.LastBootUpTime
  36.     outputFile.WriteLine "系统目录: " & osItem.WindowsDirectory
  37.     outputFile.WriteLine ""
  38. Next
  39. ' 计算机系统信息
  40. outputFile.WriteLine "【计算机系统信息】"
  41. Dim computerItems, computerItem
  42. Set computerItems = wmi.ExecQuery("Select * from Win32_ComputerSystem")
  43. For Each computerItem In computerItems
  44.     outputFile.WriteLine "制造商: " & computerItem.Manufacturer
  45.     outputFile.WriteLine "型号: " & computerItem.Model
  46.     outputFile.WriteLine "系统类型: " & computerItem.SystemType
  47.     outputFile.WriteLine "处理器数量: " & computerItem.NumberOfProcessors
  48.     outputFile.WriteLine "总物理内存: " & Round(computerItem.TotalPhysicalMemory / (1024 * 1024), 2) & " MB"
  49.     outputFile.WriteLine ""
  50. Next
  51. ' 处理器信息
  52. outputFile.WriteLine "【处理器信息】")
  53. Dim processorItems, processorItem
  54. Set processorItems = wmi.ExecQuery("Select * from Win32_Processor")
  55. For Each processorItem In processorItems
  56.     outputFile.WriteLine "处理器名称: " & processorItem.Name
  57.     outputFile.WriteLine "处理器描述: " & processorItem.Description
  58.     outputFile.WriteLine "处理器ID: " & processorItem.ProcessorId
  59.     outputFile.WriteLine "核心数量: " & processorItem.NumberOfCores
  60.     outputFile.WriteLine "逻辑处理器: " & processorItem.NumberOfLogicalProcessors
  61.     outputFile.WriteLine "最大时钟速度: " & processorItem.MaxClockSpeed & " MHz"
  62.     outputFile.WriteLine "当前时钟速度: " & processorItem.CurrentClockSpeed & " MHz"
  63.     outputFile.WriteLine ""
  64. Next
  65. ' 内存信息
  66. outputFile.WriteLine "【内存信息】")
  67. Dim memoryItems, memoryItem
  68. Set memoryItems = wmi.ExecQuery("Select * from Win32_PhysicalMemory")
  69. For Each memoryItem In memoryItems
  70.     outputFile.WriteLine "内存标签: " & memoryItem.Tag
  71.     outputFile.WriteLine "容量: " & Round(memoryItem.Capacity / (1024 * 1024), 2) & " MB"
  72.     outputFile.WriteLine "内存类型: " & GetMemoryType(memoryItem.MemoryType)
  73.     outputFile.WriteLine "速度: " & memoryItem.Speed & " MHz"
  74.     outputFile.WriteLine "制造商: " & memoryItem.Manufacturer
  75.     outputFile.WriteLine "序列号: " & memoryItem.SerialNumber
  76.     outputFile.WriteLine ""
  77. Next
  78. ' 磁盘信息
  79. outputFile.WriteLine "【磁盘信息】")
  80. Dim diskItems, diskItem
  81. Set diskItems = wmi.ExecQuery("Select * from Win32_LogicalDisk Where DriveType=3")
  82. For Each diskItem In diskItems
  83.     outputFile.WriteLine "驱动器: " & diskItem.DeviceID
  84.     outputFile.WriteLine "文件系统: " & diskItem.FileSystem
  85.     outputFile.WriteLine "总大小: " & Round(diskItem.Size / (1024 * 1024 * 1024), 2) & " GB"
  86.     outputFile.WriteLine "可用空间: " & Round(diskItem.FreeSpace / (1024 * 1024 * 1024), 2) & " GB"
  87.     outputFile.WriteLine "已用空间: " & Round((diskItem.Size - diskItem.FreeSpace) / (1024 * 1024 * 1024), 2) & " GB"
  88.     outputFile.WriteLine ""
  89. Next
  90. ' 网络适配器信息
  91. outputFile.WriteLine "【网络适配器信息】")
  92. Dim adapterItems, adapterItem
  93. Set adapterItems = wmi.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
  94. For Each adapterItem In adapterItems
  95.     outputFile.WriteLine "描述: " & adapterItem.Description
  96.     outputFile.WriteLine "MAC地址: " & adapterItem.MACAddress
  97.    
  98.     If Not IsNull(adapterItem.IPAddress) Then
  99.         outputFile.WriteLine "IP地址: " & Join(adapterItem.IPAddress, ", ")
  100.     End If
  101.    
  102.     If Not IsNull(adapterItem.IPSubnet) Then
  103.         outputFile.WriteLine "子网掩码: " & Join(adapterItem.IPSubnet, ", ")
  104.     End If
  105.    
  106.     If Not IsNull(adapterItem.DefaultIPGateway) Then
  107.         outputFile.WriteLine "默认网关: " & Join(adapterItem.DefaultIPGateway, ", ")
  108.     End If
  109.    
  110.     If Not IsNull(adapterItem.DNSServerSearchOrder) Then
  111.         outputFile.WriteLine "DNS服务器: " & Join(adapterItem.DNSServerSearchOrder, ", ")
  112.     End If
  113.    
  114.     outputFile.WriteLine "DHCP启用: " & adapterItem.DHCPEnabled
  115.    
  116.     If adapterItem.DHCPEnabled Then
  117.         outputFile.WriteLine "DHCP服务器: " & adapterItem.DHCPServer
  118.     End If
  119.    
  120.     outputFile.WriteLine ""
  121. Next
  122. ' 安装的软件
  123. outputFile.WriteLine "【安装的软件】")
  124. Dim softwareItems, softwareItem
  125. Set softwareItems = wmi.ExecQuery("Select * from Win32_Product")
  126. For Each softwareItem In softwareItems
  127.     outputFile.WriteLine "名称: " & softwareItem.Name
  128.     outputFile.WriteLine "版本: " & softwareItem.Version
  129.     outputFile.WriteLine "供应商: " & softwareItem.Vendor
  130.     outputFile.WriteLine "安装日期: " & softwareItem.InstallDate
  131.     outputFile.WriteLine ""
  132. Next
  133. ' 关闭输出文件
  134. outputFile.Close
  135. MsgBox "系统信息已收集并保存到 " & OUTPUT_FILE, vbInformation, "系统信息收集完成"
  136. ' 函数:获取内存类型
  137. Function GetMemoryType(memoryType)
  138.     Select Case memoryType
  139.         Case 0: GetMemoryType = "Unknown"
  140.         Case 1: GetMemoryType = "Other"
  141.         Case 2: GetMemoryType = "DRAM"
  142.         Case 3: GetMemoryType = "Synchronous DRAM"
  143.         Case 4: GetMemoryType = "Cache DRAM"
  144.         Case 5: GetMemoryType = "EDO"
  145.         Case 6: GetMemoryType = "EDRAM"
  146.         Case 7: GetMemoryType = "VRAM"
  147.         Case 8: GetMemoryType = "SRAM"
  148.         Case 9: GetMemoryType = "RAM"
  149.         Case 10: GetMemoryType = "ROM"
  150.         Case 11: GetMemoryType = "Flash"
  151.         Case 12: GetMemoryType = "EEPROM"
  152.         Case 13: GetMemoryType = "FEPROM"
  153.         Case 14: GetMemoryType = "EPROM"
  154.         Case 15: GetMemoryType = "CDRAM"
  155.         Case 16: GetMemoryType = "3DRAM"
  156.         Case 17: GetMemoryType = "SDRAM"
  157.         Case 18: GetMemoryType = "SGRAM"
  158.         Case 19: GetMemoryType = "RDRAM"
  159.         Case 20: GetMemoryType = "DDR"
  160.         Case 21: GetMemoryType = "DDR-2"
  161.         Case 22: GetMemoryType = "DDR-3"
  162.         Case 23: GetMemoryType = "DDR-4"
  163.         Case Else: GetMemoryType = "Unknown"
  164.     End Select
  165. End Function
复制代码

批量文件重命名工具
  1. ' 批量文件重命名工具
  2. Option Explicit
  3. ' 配置部分
  4. Const TARGET_FOLDER = "C:\Temp\RenameTest"  ' 目标文件夹
  5. Const PREFIX = "File_"                      ' 文件名前缀
  6. Const START_NUMBER = 1                      ' 起始编号
  7. Const PAD_LENGTH = 3                        ' 编号位数(不足补零)
  8. ' 主程序
  9. Dim fso, folder, files, file, newName, counter
  10. Set fso = CreateObject("Scripting.FileSystemObject")
  11. ' 检查目标文件夹是否存在
  12. If Not fso.FolderExists(TARGET_FOLDER) Then
  13.     MsgBox "目标文件夹 " & TARGET_FOLDER & " 不存在!", vbExclamation, "错误"
  14.     WScript.Quit 1
  15. End If
  16. ' 获取文件夹对象
  17. Set folder = fso.GetFolder(TARGET_FOLDER)
  18. ' 获取文件集合
  19. Set files = folder.Files
  20. ' 确认操作
  21. If MsgBox("确定要重命名文件夹 " & TARGET_FOLDER & " 中的所有文件吗?" & vbCrLf & _
  22.           "文件数量: " & files.Count, vbQuestion + vbYesNo, "确认") = vbNo Then
  23.     WScript.Quit
  24. End If
  25. ' 初始化计数器
  26. counter = START_NUMBER
  27. ' 遍历文件并重命名
  28. For Each file In files
  29.     ' 跳过脚本文件本身
  30.     If InStr(1, WScript.ScriptFullName, file.Path, vbTextCompare) = 0 Then
  31.         ' 构建新文件名
  32.         newName = PREFIX & PadNumber(counter, PAD_LENGTH) & "." & fso.GetExtensionName(file.Name)
  33.         
  34.         ' 检查新文件名是否已存在
  35.         If fso.FileExists(folder.Path & "" & newName) Then
  36.             MsgBox "文件 " & newName & " 已存在,跳过重命名 " & file.Name, vbExclamation, "警告"
  37.         Else
  38.             ' 重命名文件
  39.             file.Name = newName
  40.             MsgBox "已重命名: " & file.Name & " -> " & newName, vbInformation, "重命名"
  41.         End If
  42.         
  43.         ' 增加计数器
  44.         counter = counter + 1
  45.     End If
  46. Next
  47. MsgBox "批量重命名完成!", vbInformation, "完成"
  48. ' 函数:数字补零
  49. Function PadNumber(number, length)
  50.     Dim result, i
  51.     result = CStr(number)
  52.    
  53.     ' 如果数字长度不足指定长度,前面补零
  54.     For i = Len(result) To length - 1
  55.         result = "0" & result
  56.     Next
  57.    
  58.     PadNumber = result
  59. End Function
复制代码

高级技巧与最佳实践

代码组织与模块化
  1. ' 使用Include模拟文件包含(VBScript本身不支持)
  2. Sub IncludeFile(filePath)
  3.     Dim fso, file, content
  4.     Set fso = CreateObject("Scripting.FileSystemObject")
  5.    
  6.     If fso.FileExists(filePath) Then
  7.         Set file = fso.OpenTextFile(filePath, 1)  ' 1表示只读
  8.         content = file.ReadAll
  9.         file.Close
  10.         
  11.         ExecuteGlobal content  ' 执行包含的代码
  12.     Else
  13.         MsgBox "无法包含文件: " & filePath, vbExclamation, "错误"
  14.     End If
  15. End Sub
  16. ' 模拟类定义
  17. Class Person
  18.     ' 私有变量
  19.     Private m_Name
  20.     Private m_Age
  21.    
  22.     ' 构造函数
  23.     Public Sub Class_Initialize
  24.         m_Name = ""
  25.         m_Age = 0
  26.     End Sub
  27.    
  28.     ' 属性:Name
  29.     Public Property Get Name
  30.         Name = m_Name
  31.     End Property
  32.    
  33.     Public Property Let Name(value)
  34.         m_Name = value
  35.     End Property
  36.    
  37.     ' 属性:Age
  38.     Public Property Get Age
  39.         Age = m_Age
  40.     End Property
  41.    
  42.     Public Property Let Age(value)
  43.         If IsNumeric(value) And value >= 0 Then
  44.             m_Age = CInt(value)
  45.         Else
  46.             MsgBox "年龄必须是正数", vbExclamation, "错误"
  47.         End If
  48.     End Property
  49.    
  50.     ' 方法:介绍自己
  51.     Public Sub Introduce()
  52.         MsgBox "你好,我叫 " & m_Name & ",今年 " & m_Age & " 岁。", vbInformation, "自我介绍"
  53.     End Sub
  54. End Class
  55. ' 使用类
  56. Dim person
  57. Set person = New Person
  58. person.Name = "张三"
  59. person.Age = 30
  60. person.Introduce()
复制代码

性能优化
  1. ' 性能优化示例
  2. ' 1. 使用With语句减少对象引用
  3. Sub WithExample()
  4.     Dim fso, file
  5.     Set fso = CreateObject("Scripting.FileSystemObject")
  6.    
  7.     ' 不优化的写法
  8.     Set file = fso.CreateTextFile("C:\Temp\test1.txt")
  9.     file.WriteLine("Line 1")
  10.     file.WriteLine("Line 2")
  11.     file.WriteLine("Line 3")
  12.     file.Close
  13.    
  14.     ' 优化的写法
  15.     With fso.CreateTextFile("C:\Temp\test2.txt")
  16.         .WriteLine("Line 1")
  17.         .WriteLine("Line 2")
  18.         .WriteLine("Line 3")
  19.         .Close
  20.     End With
  21. End Sub
  22. ' 2. 避免在循环中重复创建对象
  23. Sub AvoidObjectCreationInLoop()
  24.     Dim fso, i
  25.     Set fso = CreateObject("Scripting.FileSystemObject")
  26.    
  27.     ' 不优化的写法
  28.     For i = 1 To 10
  29.         Dim file1
  30.         Set file1 = CreateObject("Scripting.FileSystemObject").CreateTextFile("C:\Temp\file" & i & ".txt")
  31.         file1.WriteLine("Content for file " & i)
  32.         file1.Close
  33.     Next
  34.    
  35.     ' 优化的写法
  36.     For i = 11 To 20
  37.         Dim file2
  38.         Set file2 = fso.CreateTextFile("C:\Temp\file" & i & ".txt")
  39.         file2.WriteLine("Content for file " & i)
  40.         file2.Close
  41.     Next
  42. End Sub
  43. ' 3. 使用数组代替字符串连接(处理大量数据时)
  44. Sub StringConcatenationOptimization()
  45.     Dim i, startTime, endTime, duration, result
  46.    
  47.     ' 测试字符串连接的性能
  48.     startTime = Timer
  49.    
  50.     result = ""
  51.     For i = 1 To 10000
  52.         result = result & "Line " & i & vbCrLf
  53.     Next
  54.    
  55.     endTime = Timer
  56.     duration = endTime - startTime
  57.     MsgBox "字符串连接耗时: " & duration & " 秒", vbInformation, "性能测试"
  58.    
  59.     ' 测试数组连接的性能
  60.     startTime = Timer
  61.    
  62.     Dim lines()
  63.     ReDim lines(10000)
  64.    
  65.     For i = 1 To 10000
  66.         lines(i-1) = "Line " & i
  67.     Next
  68.    
  69.     result = Join(lines, vbCrLf)
  70.    
  71.     endTime = Timer
  72.     duration = endTime - startTime
  73.     MsgBox "数组连接耗时: " & duration & " 秒", vbInformation, "性能测试"
  74. End Sub
复制代码

调试技巧
  1. ' 调试技巧示例
  2. ' 1. 使用消息框进行简单调试
  3. Sub DebugWithMsgBox()
  4.     Dim x, y, result
  5.     x = 10
  6.     y = 0
  7.    
  8.     On Error Resume Next
  9.     result = x / y
  10.    
  11.     If Err.Number <> 0 Then
  12.         MsgBox "错误 #" & Err.Number & ": " & Err.Description & vbCrLf & _
  13.                "发生在: " & Err.Source, vbExclamation, "调试信息"
  14.         Err.Clear
  15.     Else
  16.         MsgBox "计算结果: " & result, vbInformation, "调试信息"
  17.     End If
  18.    
  19.     On Error GoTo 0
  20. End Sub
  21. ' 2. 写入日志文件进行调试
  22. Sub DebugWithLogFile()
  23.     Dim fso, logFile
  24.     Set fso = CreateObject("Scripting.FileSystemObject")
  25.    
  26.     ' 创建或打开日志文件
  27.     Set logFile = fso.OpenTextFile("C:\Temp\debug_log.txt", 8, True)  ' 8表示追加模式
  28.    
  29.     ' 写入调试信息
  30.     logFile.WriteLine Now & " - 脚本开始执行"
  31.    
  32.     Dim i
  33.     For i = 1 To 5
  34.         logFile.WriteLine Now & " - 循环计数: " & i
  35.     Next
  36.    
  37.     logFile.WriteLine Now & " - 脚本执行完成"
  38.    
  39.     ' 关闭日志文件
  40.     logFile.Close
  41.    
  42.     MsgBox "调试信息已写入日志文件", vbInformation, "调试"
  43. End Sub
  44. ' 3. 条件编译调试代码
  45. Sub ConditionalCompilation()
  46.     ' 定义调试常量
  47.     Const DEBUG_MODE = True
  48.    
  49.     ' 主代码
  50.     Dim x, y, result
  51.     x = 10
  52.     y = 5
  53.     result = x + y
  54.    
  55.     ' 调试代码
  56.     #If DEBUG_MODE Then
  57.         MsgBox "x = " & x & vbCrLf & "y = " & y & vbCrLf & "result = " & result, vbInformation, "调试信息"
  58.     #End If
  59. End Sub
复制代码

安全性考虑
  1. ' 安全性考虑示例
  2. ' 1. 输入验证
  3. Sub ValidateInput()
  4.     Dim userInput
  5.     userInput = InputBox("请输入一个数字:", "输入验证")
  6.    
  7.     ' 验证输入是否为数字
  8.     If Not IsNumeric(userInput) Then
  9.         MsgBox "请输入有效的数字!", vbExclamation, "输入错误"
  10.         Exit Sub
  11.     End If
  12.    
  13.     ' 验证数字范围
  14.     Dim number
  15.     number = CDbl(userInput)
  16.    
  17.     If number < 0 Or number > 100 Then
  18.         MsgBox "请输入0到100之间的数字!", vbExclamation, "输入错误"
  19.         Exit Sub
  20.     End If
  21.    
  22.     MsgBox "输入验证通过: " & number, vbInformation, "验证成功"
  23. End Sub
  24. ' 2. 安全处理文件路径
  25. Sub SafeFilePathHandling()
  26.     Dim userInput
  27.     userInput = InputBox("请输入文件名:", "文件路径安全处理")
  28.    
  29.     ' 移除潜在危险的字符
  30.     Dim safeFileName
  31.     safeFileName = userInput
  32.     safeFileName = Replace(safeFileName, "..", "")  ' 移除路径遍历
  33.     safeFileName = Replace(safeFileName, "/", "")   ' 移除路径分隔符
  34.     safeFileName = Replace(safeFileName, "", "")   ' 移除路径分隔符
  35.     safeFileName = Replace(safeFileName, ":", "")   ' 移除驱动器指示符
  36.     safeFileName = Replace(safeFileName, "*", "")   ' 移除通配符
  37.     safeFileName = Replace(safeFileName, "?", "")   ' 移除通配符
  38.     safeFileName = Replace(safeFileName, """", "")  ' 移除引号
  39.     safeFileName = Replace(safeFileName, "<", "")    ' 移除HTML特殊字符
  40.     safeFileName = Replace(safeFileName, ">", "")    ' 移除HTML特殊字符
  41.     safeFileName = Replace(safeFileName, "|", "")    ' 移除管道符
  42.    
  43.     MsgBox "原始输入: " & userInput & vbCrLf & _
  44.            "安全文件名: " & safeFileName, vbInformation, "安全处理"
  45. End Sub
  46. ' 3. 安全执行外部命令
  47. Sub SafeCommandExecution()
  48.     Dim command, allowedCommands
  49.     allowedCommands = Array("notepad.exe", "calc.exe", "mspaint.exe")
  50.    
  51.     command = InputBox("请输入要执行的命令 (如 notepad.exe):", "安全命令执行")
  52.    
  53.     ' 验证命令是否在允许列表中
  54.     Dim isAllowed, cmd
  55.     isAllowed = False
  56.    
  57.     For Each cmd In allowedCommands
  58.         If LCase(command) = LCase(cmd) Then
  59.             isAllowed = True
  60.             Exit For
  61.         End If
  62.     Next
  63.    
  64.     If Not isAllowed Then
  65.         MsgBox "不允许执行命令: " & command, vbExclamation, "安全错误"
  66.         Exit Sub
  67.     End If
  68.    
  69.     ' 执行命令
  70.     Dim wshShell
  71.     Set wshShell = CreateObject("WScript.Shell")
  72.     wshShell.Run command
  73.    
  74.     MsgBox "命令已执行: " & command, vbInformation, "执行成功"
  75. End Sub
复制代码

总结与进阶学习路径

本文总结

本文详细介绍了VBScript的基础知识和高级应用,从基本语法、数据类型、控制结构,到文件系统操作、Windows系统交互、数据库操作等,并通过实际应用案例展示了VBScript的强大功能。通过学习本文,你已经掌握了VBScript的核心技术,具备了使用VBScript解决实际问题的能力。

进阶学习路径

1. 深入学习Windows Management Instrumentation (WMI)WMI是Windows管理的核心技术,通过VBScript可以充分利用WMI进行系统管理学习WMI查询语言(WQL)和WMI类结构探索更多WMI命名空间和类
2. WMI是Windows管理的核心技术,通过VBScript可以充分利用WMI进行系统管理
3. 学习WMI查询语言(WQL)和WMI类结构
4. 探索更多WMI命名空间和类
5. 学习Active Directory管理使用VBScript通过ADSI (Active Directory Service Interfaces)管理Active Directory用户和组管理、策略应用等
6. 使用VBScript通过ADSI (Active Directory Service Interfaces)管理Active Directory
7. 用户和组管理、策略应用等
8. 探索更多COM组件VBScript可以调用各种COM组件扩展功能学习Microsoft Office自动化、XML处理等
9. VBScript可以调用各种COM组件扩展功能
10. 学习Microsoft Office自动化、XML处理等
11. 结合PowerShell使用PowerShell是现代Windows管理的首选工具学习如何在PowerShell中调用VBScript,以及如何将VBScript迁移到PowerShell
12. PowerShell是现代Windows管理的首选工具
13. 学习如何在PowerShell中调用VBScript,以及如何将VBScript迁移到PowerShell
14. 学习其他脚本语言JavaScript、Python等现代脚本语言比较不同语言的优缺点,选择最适合的工具
15. JavaScript、Python等现代脚本语言
16. 比较不同语言的优缺点,选择最适合的工具

深入学习Windows Management Instrumentation (WMI)

• WMI是Windows管理的核心技术,通过VBScript可以充分利用WMI进行系统管理
• 学习WMI查询语言(WQL)和WMI类结构
• 探索更多WMI命名空间和类

学习Active Directory管理

• 使用VBScript通过ADSI (Active Directory Service Interfaces)管理Active Directory
• 用户和组管理、策略应用等

探索更多COM组件

• VBScript可以调用各种COM组件扩展功能
• 学习Microsoft Office自动化、XML处理等

结合PowerShell使用

• PowerShell是现代Windows管理的首选工具
• 学习如何在PowerShell中调用VBScript,以及如何将VBScript迁移到PowerShell

学习其他脚本语言

• JavaScript、Python等现代脚本语言
• 比较不同语言的优缺点,选择最适合的工具

推荐资源

1. Microsoft官方文档VBScript用户指南Windows Script Host文档WMI和ADSI文档
2. VBScript用户指南
3. Windows Script Host文档
4. WMI和ADSI文档
5. 在线教程和社区Microsoft Script CenterStack OverflowVBScript论坛和社区
6. Microsoft Script Center
7. Stack Overflow
8. VBScript论坛和社区
9. 参考书籍《VBScript程序员参考》《Windows系统管理脚本编程》《WMI技术指南》
10. 《VBScript程序员参考》
11. 《Windows系统管理脚本编程》
12. 《WMI技术指南》

Microsoft官方文档

• VBScript用户指南
• Windows Script Host文档
• WMI和ADSI文档

在线教程和社区

• Microsoft Script Center
• Stack Overflow
• VBScript论坛和社区

参考书籍

• 《VBScript程序员参考》
• 《Windows系统管理脚本编程》
• 《WMI技术指南》

结语

VBScript作为一种成熟的脚本语言,在Windows系统管理和自动化领域仍然具有重要价值。通过本文的学习,你已经掌握了VBScript的基础知识和应用技巧,可以开始编写自己的脚本解决实际问题。记住,编程是一门实践性很强的技能,只有不断练习和实践,才能真正掌握它。希望你在VBScript的学习和实践中取得成功!
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则