简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索
AI 风月

活动公告

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

轻松掌握VBScript应用从零开始学习这一强大脚本语言助您在日常工作中实现自动化提高工作效率解决实际问题

3万

主题

602

科技点

3万

积分

白金月票

碾压王

积分
32704

立华奏

发表于 2025-9-20 13:40:00 | 显示全部楼层 |阅读模式

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

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

x
引言:什么是VBScript及其重要性

VBScript(Visual Basic Scripting Edition)是一种由微软开发的轻量级脚本语言,它是Visual Basic家族的成员。作为一种解释型脚本语言,VBScript不需要编译即可运行,特别适合用于自动化任务、系统管理和网页开发。在Windows环境中,VBScript可以访问操作系统的许多功能,使其成为自动化日常任务的理想选择。

VBScript的重要性体现在以下几个方面:

• 易于学习:语法简单,对于有编程基础的人来说很容易上手
• 广泛兼容:在Windows系统中内置支持,无需额外安装
• 功能强大:可以访问文件系统、注册表、网络等系统资源
• 自动化能力:能够自动执行重复性任务,提高工作效率

VBScript基础语法

第一个VBScript程序

让我们从经典的”Hello, World!“程序开始:
  1. ' 这是一个简单的VBScript程序
  2. MsgBox "Hello, World!"
复制代码

将以上代码保存为.vbs文件(例如hello.vbs),然后双击运行,您将看到一个弹出窗口显示”Hello, World!“。

基本语法规则

VBScript的语法规则相对简单:

1. 注释:使用单引号(')来添加注释
2. 大小写不敏感:VBScript不区分大小写
3. 语句分隔:每行通常一个语句,多个语句可用冒号(:)分隔
4. 续行:使用下划线(_)将长语句分成多行
  1. ' 注释示例
  2. ' 下面的代码演示了语句分隔和续行
  3. MsgBox "第一条语句" : MsgBox "第二条语句"
  4. MsgBox "这是一个很长的消息," & _
  5.        "所以使用了续行符将其分成两行"
复制代码

变量和数据类型

变量声明与使用

在VBScript中,可以使用Dim、Private或Public语句声明变量。虽然VBScript允许不声明变量直接使用,但良好的编程习惯是先声明后使用。
  1. ' 声明变量
  2. Dim userName
  3. Dim age, email  ' 可以一次声明多个变量
  4. ' 赋值
  5. userName = "张三"
  6. age = 30
  7. email = "zhangsan@example.com"
  8. ' 使用变量
  9. MsgBox "用户名: " & userName & vbCrLf & _
  10.        "年龄: " & age & vbCrLf & _
  11.        "邮箱: " & email
复制代码

数据类型

VBScript只有一种数据类型,称为Variant,它可以包含不同类型的信息。Variant的子类型包括:

• Empty:未初始化
• Null:不包含有效数据
• Boolean:True或False
• Byte:0到255的整数
• Integer:-32,768到32,767的整数
• Long:-2,147,483,648到2,147,483,647的整数
• Single:单精度浮点数
• Double:双精度浮点数
• Date:日期和时间
• String:字符串
• Object:对象
• Error:错误号
  1. ' 不同数据类型的示例
  2. Dim varEmpty, varNull, varBoolean, varInteger
  3. Dim varLong, varDouble, varDate, varString
  4. ' Empty类型(未初始化)
  5. MsgBox "varEmpty的类型是: " & TypeName(varEmpty)
  6. ' Null类型
  7. varNull = Null
  8. MsgBox "varNull的类型是: " & TypeName(varNull)
  9. ' Boolean类型
  10. varBoolean = True
  11. MsgBox "varBoolean的类型是: " & TypeName(varBoolean) & ",值是: " & varBoolean
  12. ' Integer类型
  13. varInteger = 100
  14. MsgBox "varInteger的类型是: " & TypeName(varInteger) & ",值是: " & varInteger
  15. ' Long类型
  16. varLong = 100000
  17. MsgBox "varLong的类型是: " & TypeName(varLong) & ",值是: " & varLong
  18. ' Double类型
  19. varDouble = 3.1415926535
  20. MsgBox "varDouble的类型是: " & TypeName(varDouble) & ",值是: " & varDouble
  21. ' Date类型
  22. varDate = Now()
  23. MsgBox "varDate的类型是: " & TypeName(varDate) & ",值是: " & varDate
  24. ' String类型
  25. varString = "这是一个字符串"
  26. MsgBox "varString的类型是: " & TypeName(varString) & ",值是: " & varString
复制代码

变量作用域

VBScript中的变量有不同的作用域:

• 脚本级变量:在所有过程外声明,整个脚本都可以访问
• 过程级变量:在过程内声明,只在该过程内有效
  1. ' 脚本级变量
  2. Dim scriptLevelVar
  3. scriptLevelVar = "我是脚本级变量"
  4. ' 子程序
  5. Sub ShowVariables()
  6.     ' 过程级变量
  7.     Dim procedureLevelVar
  8.     procedureLevelVar = "我是过程级变量"
  9.    
  10.     MsgBox "在子程序中:" & vbCrLf & _
  11.            "scriptLevelVar = " & scriptLevelVar & vbCrLf & _
  12.            "procedureLevelVar = " & procedureLevelVar
  13. End Sub
  14. ' 调用子程序
  15. Call ShowVariables()
  16. ' 尝试访问过程级变量(会出错)
  17. On Error Resume Next
  18. MsgBox "在脚本级别:" & vbCrLf & _
  19.        "scriptLevelVar = " & scriptLevelVar & vbCrLf & _
  20.        "procedureLevelVar = " & procedureLevelVar
  21. If Err.Number <> 0 Then
  22.     MsgBox "错误: " & Err.Description
  23. End If
  24. On Error GoTo 0
复制代码

控制结构

条件语句

VBScript提供了多种条件语句,包括If...Then...Else和Select Case。
  1. ' 简单If语句
  2. Dim score
  3. score = 85
  4. If score >= 60 Then
  5.     MsgBox "恭喜!您通过了考试。"
  6. End If
  7. ' If...Else语句
  8. If score >= 60 Then
  9.     MsgBox "恭喜!您通过了考试。"
  10. Else
  11.     MsgBox "很遗憾,您没有通过考试。"
  12. End If
  13. ' If...ElseIf...Else语句
  14. If score >= 90 Then
  15.     MsgBox "优秀!"
  16. ElseIf score >= 80 Then
  17.     MsgBox "良好!"
  18. ElseIf score >= 70 Then
  19.     MsgBox "中等!"
  20. ElseIf score >= 60 Then
  21.     MsgBox "及格!"
  22. Else
  23.     MsgBox "不及格!"
  24. End If
复制代码

当需要根据一个表达式的多个可能值执行不同操作时,Select Case语句比多个ElseIf更清晰。
  1. ' Select Case示例
  2. Dim dayOfWeek
  3. dayOfWeek = Weekday(Now())
  4. Select Case dayOfWeek
  5.     Case 1
  6.         MsgBox "今天是星期日"
  7.     Case 2
  8.         MsgBox "今天是星期一"
  9.     Case 3
  10.         MsgBox "今天是星期二"
  11.     Case 4
  12.         MsgBox "今天是星期三"
  13.     Case 5
  14.         MsgBox "今天是星期四"
  15.     Case 6
  16.         MsgBox "今天是星期五"
  17.     Case 7
  18.         MsgBox "今天是星期六"
  19.     Case Else
  20.         MsgBox "无效的日期"
  21. End Select
  22. ' 使用比较运算符的Select Case
  23. Dim temperature
  24. temperature = 25
  25. Select Case True
  26.     Case temperature < 0
  27.         MsgBox "严寒"
  28.     Case temperature < 10
  29.         MsgBox "寒冷"
  30.     Case temperature < 20
  31.         MsgBox "凉爽"
  32.     Case temperature < 30
  33.         MsgBox "温暖"
  34.     Case Else
  35.         MsgBox "炎热"
  36. End Select
复制代码

循环语句

VBScript提供了多种循环结构,包括Do...Loop、While...Wend、For...Next和For Each...Next。
  1. ' Do While...Loop(先判断后执行)
  2. Dim counter
  3. counter = 1
  4. Do While counter <= 5
  5.     MsgBox "计数器值: " & counter
  6.     counter = counter + 1
  7. Loop
  8. ' Do...Loop While(先执行后判断)
  9. counter = 1
  10. Do
  11.     MsgBox "计数器值: " & counter
  12.     counter = counter + 1
  13. Loop While counter <= 5
  14. ' Do Until...Loop(直到条件为真时停止)
  15. counter = 1
  16. Do Until counter > 5
  17.     MsgBox "计数器值: " & counter
  18.     counter = counter + 1
  19. Loop
  20. ' Do...Loop Until(先执行后判断)
  21. counter = 1
  22. Do
  23.     MsgBox "计数器值: " & counter
  24.     counter = counter + 1
  25. Loop Until counter > 5
复制代码
  1. ' While...Wend循环
  2. counter = 1
  3. While counter <= 5
  4.     MsgBox "计数器值: " & counter
  5.     counter = counter + 1
  6. Wend
复制代码
  1. ' 基本的For...Next循环
  2. Dim i
  3. For i = 1 To 5
  4.     MsgBox "循环计数: " & i
  5. Next
  6. ' 带步长的For...Next循环
  7. For i = 1 To 10 Step 2
  8.     MsgBox "循环计数: " & i
  9. Next
  10. ' 递减的For...Next循环
  11. For i = 10 To 1 Step -1
  12.     MsgBox "倒计时: " & i
  13. Next
  14. ' 嵌套的For...Next循环
  15. Dim j
  16. For i = 1 To 3
  17.     For j = 1 To 3
  18.         MsgBox "i = " & i & ", j = " & j
  19.     Next
  20. Next
复制代码
  1. ' For Each...Next循环用于遍历集合或数组
  2. Dim drives, drive
  3. Set drives = CreateObject("Scripting.FileSystemObject").Drives
  4. For Each drive In drives
  5.     MsgBox "驱动器 " & drive.DriveLetter & ": " & _
  6.            "可用空间: " & FormatNumber(drive.AvailableSpace / 1024 / 1024, 2) & " MB"
  7. Next
复制代码

函数和子程序

子程序(Sub)

子程序是执行特定任务但不返回值的代码块。
  1. ' 定义子程序
  2. Sub ShowWelcomeMessage(name)
  3.     MsgBox "欢迎, " & name & "!"
  4. End Sub
  5. ' 调用子程序
  6. Call ShowWelcomeMessage("张三")
  7. ' 或者不使用Call关键字
  8. ShowWelcomeMessage("李四")
  9. ' 带参数的子程序
  10. Sub CalculateSum(a, b)
  11.     MsgBox a & " + " & b & " = " & (a + b)
  12. End Sub
  13. CalculateSum 10, 20
  14. ' 带可选参数的子程序
  15. Sub Greet(name, Optional greeting = "你好")
  16.     MsgBox greeting & ", " & name & "!"
  17. End Sub
  18. Greet "王五"
  19. Greet "赵六", "早上好"
复制代码

函数(Function)

函数是执行特定任务并返回值的代码块。
  1. ' 定义函数
  2. Function GetFullName(firstName, lastName)
  3.     GetFullName = firstName & " " & lastName
  4. End Function
  5. ' 使用函数
  6. Dim fullName
  7. fullName = GetFullName("张", "三")
  8. MsgBox "全名: " & fullName
  9. ' 带参数验证的函数
  10. Function Divide(a, b)
  11.     If b = 0 Then
  12.         Divide = "错误:除数不能为零"
  13.     Else
  14.         Divide = a / b
  15.     End If
  16. End Function
  17. MsgBox "10 / 2 = " & Divide(10, 2)
  18. MsgBox "10 / 0 = " & Divide(10, 0)
  19. ' 递归函数示例
  20. Function Factorial(n)
  21.     If n = 0 Or n = 1 Then
  22.         Factorial = 1
  23.     Else
  24.         Factorial = n * Factorial(n - 1)
  25.     End If
  26. End Function
  27. MsgBox "5的阶乘是: " & Factorial(5)
复制代码

内置函数

VBScript提供了许多内置函数,用于处理字符串、日期、数学运算等。
  1. Dim str
  2. str = "Hello, World!"
  3. ' 字符串长度
  4. MsgBox "字符串长度: " & Len(str)
  5. ' 转换为大写和小写
  6. MsgBox "大写: " & UCase(str)
  7. MsgBox "小写: " & LCase(str)
  8. ' 去除空格
  9. Dim strWithSpaces
  10. strWithSpaces = "  前后有空格  "
  11. MsgBox "原字符串: '" & strWithSpaces & "'"
  12. MsgBox "去除空格: '" & Trim(strWithSpaces) & "'"
  13. ' 字符串截取
  14. MsgBox "前5个字符: " & Left(str, 5)
  15. MsgBox "后6个字符: " & Right(str, 6)
  16. MsgBox "从第8个位置开始的5个字符: " & Mid(str, 8, 5)
  17. ' 字符串替换
  18. MsgBox "替换前: " & str
  19. MsgBox "替换后: " & Replace(str, "World", "VBScript")
  20. ' 字符串分割
  21. Dim parts, i
  22. parts = Split("apple,banana,orange", ",")
  23. For i = 0 To UBound(parts)
  24.     MsgBox "部分 " & i & ": " & parts(i)
  25. Next
  26. ' 字符串连接
  27. Dim fruits
  28. fruits = Join(parts, " | ")
  29. MsgBox "连接后的字符串: " & fruits
复制代码
  1. ' 获取当前日期和时间
  2. MsgBox "当前日期: " & Date()
  3. MsgBox "当前时间: " & Time()
  4. MsgBox "当前日期和时间: " & Now()
  5. ' 日期部分
  6. MsgBox "年: " & Year(Now())
  7. MsgBox "月: " & Month(Now())
  8. MsgBox "日: " & Day(Now())
  9. MsgBox "星期几: " & Weekday(Now())
  10. MsgBox "小时: " & Hour(Now())
  11. MsgBox "分钟: " & Minute(Now())
  12. MsgBox "秒: " & Second(Now())
  13. ' 日期计算
  14. MsgBox "明天: " & DateAdd("d", 1, Date())
  15. MsgBox "下个月: " & DateAdd("m", 1, Date())
  16. MsgBox "明年: " & DateAdd("yyyy", 1, Date())
  17. ' 日期差值
  18. Dim startDate, endDate
  19. startDate = #1/1/2023#
  20. endDate = #12/31/2023#
  21. MsgBox "两个日期之间的天数: " & DateDiff("d", startDate, endDate)
  22. ' 格式化日期
  23. MsgBox "格式化日期: " & FormatDateTime(Now(), vbLongDate)
  24. MsgBox "格式化时间: " & FormatDateTime(Now(), vbLongTime)
复制代码
  1. ' 基本数学运算
  2. MsgBox "绝对值: " & Abs(-10.5)
  3. MsgBox "平方根: " & Sqr(16)
  4. MsgBox "指数: " & Exp(1)
  5. MsgBox "对数: " & Log(10)
  6. MsgBox "正弦: " & Sin(3.1415926535 / 2)
  7. MsgBox "余弦: " & Cos(0)
  8. MsgBox "正切: " & Tan(3.1415926535 / 4)
  9. ' 随机数
  10. Randomize  ' 初始化随机数生成器
  11. MsgBox "随机数: " & Rnd()  ' 0到1之间的随机数
  12. MsgBox "1到100之间的随机整数: " & Int(Rnd() * 100) + 1
  13. ' 数值格式化
  14. MsgBox "格式化数字: " & FormatNumber(1234.5678, 2)
  15. MsgBox "格式化货币: " & FormatCurrency(1234.5678, 2)
  16. MsgBox "格式化百分比: " & FormatPercent(0.1234, 2)
复制代码

文件操作

VBScript可以通过Scripting.FileSystemObject对象进行文件系统操作,包括创建、读取、写入和删除文件及文件夹。

文件系统对象基础
  1. ' 创建文件系统对象
  2. Dim fso
  3. Set fso = CreateObject("Scripting.FileSystemObject")
  4. ' 检查文件是否存在
  5. Dim filePath
  6. filePath = "C:\Temp\test.txt"
  7. If fso.FileExists(filePath) Then
  8.     MsgBox "文件存在: " & filePath
  9. Else
  10.     MsgBox "文件不存在: " & filePath
  11. End If
  12. ' 检查文件夹是否存在
  13. Dim folderPath
  14. folderPath = "C:\Temp"
  15. If fso.FolderExists(folderPath) Then
  16.     MsgBox "文件夹存在: " & folderPath
  17. Else
  18.     MsgBox "文件夹不存在: " & folderPath
  19. End If
  20. ' 获取文件信息
  21. If fso.FileExists(filePath) Then
  22.     Dim file
  23.     Set file = fso.GetFile(filePath)
  24.    
  25.     MsgBox "文件信息:" & vbCrLf & _
  26.            "路径: " & file.Path & vbCrLf & _
  27.            "大小: " & file.Size & " 字节" & vbCrLf & _
  28.            "创建时间: " & file.DateCreated & vbCrLf & _
  29.            "最后修改时间: " & file.DateLastModified & vbCrLf & _
  30.            "最后访问时间: " & file.DateLastAccessed
  31. End If
  32. ' 获取文件夹信息
  33. If fso.FolderExists(folderPath) Then
  34.     Dim folder
  35.     Set folder = fso.GetFolder(folderPath)
  36.    
  37.     MsgBox "文件夹信息:" & vbCrLf & _
  38.            "路径: " & folder.Path & vbCrLf & _
  39.            "大小: " & folder.Size & " 字节" & vbCrLf & _
  40.            "文件数: " & folder.Files.Count & vbCrLf & _
  41.            "子文件夹数: " & folder.SubFolders.Count
  42. End If
复制代码

创建和写入文件
  1. ' 创建文件系统对象
  2. Dim fso
  3. Set fso = CreateObject("Scripting.FileSystemObject")
  4. ' 创建文本文件并写入内容
  5. Dim filePath, file
  6. filePath = "C:\Temp\test.txt"
  7. ' 检查文件夹是否存在,不存在则创建
  8. Dim folderPath
  9. folderPath = "C:\Temp"
  10. If Not fso.FolderExists(folderPath) Then
  11.     fso.CreateFolder(folderPath)
  12.     MsgBox "已创建文件夹: " & folderPath
  13. End If
  14. ' 创建文件并写入内容
  15. Set file = fso.CreateTextFile(filePath, True)  ' True表示可以覆盖已存在的文件
  16. file.WriteLine "这是第一行"
  17. file.WriteLine "这是第二行"
  18. file.Write "这是第三行,没有换行"
  19. file.Close
  20. MsgBox "已创建文件并写入内容: " & filePath
  21. ' 追加内容到文件
  22. If fso.FileExists(filePath) Then
  23.     Set file = fso.OpenTextFile(filePath, 8)  ' 8表示追加模式
  24.     file.WriteLine vbCrLf & "这是追加的第四行"
  25.     file.Close
  26.     MsgBox "已追加内容到文件: " & filePath
  27. End If
复制代码

读取文件
  1. ' 创建文件系统对象
  2. Dim fso
  3. Set fso = CreateObject("Scripting.FileSystemObject")
  4. ' 读取整个文件
  5. Dim filePath, file, content
  6. filePath = "C:\Temp\test.txt"
  7. If fso.FileExists(filePath) Then
  8.     Set file = fso.OpenTextFile(filePath, 1)  ' 1表示只读模式
  9.     content = file.ReadAll
  10.     file.Close
  11.    
  12.     MsgBox "文件内容:" & vbCrLf & content
  13. End If
  14. ' 逐行读取文件
  15. If fso.FileExists(filePath) Then
  16.     Set file = fso.OpenTextFile(filePath, 1)
  17.     Dim lines, line
  18.     lines = ""
  19.    
  20.     Do Until file.AtEndOfStream
  21.         line = file.ReadLine
  22.         lines = lines & line & vbCrLf
  23.     Loop
  24.    
  25.     file.Close
  26.     MsgBox "逐行读取的文件内容:" & vbCrLf & lines
  27. End If
  28. ' 读取指定数量的字符
  29. If fso.FileExists(filePath) Then
  30.     Set file = fso.OpenTextFile(filePath, 1)
  31.     Dim chars
  32.     chars = file.Read(10)  ' 读取前10个字符
  33.     file.Close
  34.    
  35.     MsgBox "前10个字符: " & chars
  36. End If
复制代码

文件和文件夹操作
  1. ' 创建文件系统对象
  2. Dim fso
  3. Set fso = CreateObject("Scripting.FileSystemObject")
  4. ' 创建文件夹
  5. Dim newFolderPath
  6. newFolderPath = "C:\Temp\NewFolder"
  7. If Not fso.FolderExists(newFolderPath) Then
  8.     fso.CreateFolder(newFolderPath)
  9.     MsgBox "已创建文件夹: " & newFolderPath
  10. Else
  11.     MsgBox "文件夹已存在: " & newFolderPath
  12. End If
  13. ' 复制文件
  14. Dim sourceFile, destFile
  15. sourceFile = "C:\Temp\test.txt"
  16. destFile = "C:\Temp\NewFolder\test_copy.txt"
  17. If fso.FileExists(sourceFile) Then
  18.     fso.CopyFile sourceFile, destFile, True  ' True表示可以覆盖已存在的文件
  19.     MsgBox "已复制文件: " & sourceFile & " -> " & destFile
  20. End If
  21. ' 移动文件
  22. If fso.FileExists(destFile) Then
  23.     Dim movedFile
  24.     movedFile = "C:\Temp\NewFolder\test_moved.txt"
  25.    
  26.     fso.MoveFile destFile, movedFile
  27.     MsgBox "已移动文件: " & destFile & " -> " & movedFile
  28. End If
  29. ' 删除文件
  30. If fso.FileExists(movedFile) Then
  31.     fso.DeleteFile movedFile
  32.     MsgBox "已删除文件: " & movedFile
  33. End If
  34. ' 复制文件夹
  35. Dim sourceFolder, destFolder
  36. sourceFolder = "C:\Temp\NewFolder"
  37. destFolder = "C:\Temp\NewFolderCopy"
  38. If fso.FolderExists(sourceFolder) Then
  39.     fso.CopyFolder sourceFolder, destFolder, True
  40.     MsgBox "已复制文件夹: " & sourceFolder & " -> " & destFolder
  41. End If
  42. ' 删除文件夹
  43. If fso.FolderExists(destFolder) Then
  44.     fso.DeleteFolder destFolder
  45.     MsgBox "已删除文件夹: " & destFolder
  46. End If
  47. If fso.FolderExists(newFolderPath) Then
  48.     fso.DeleteFolder newFolderPath
  49.     MsgBox "已删除文件夹: " & newFolderPath
  50. End If
复制代码

与系统交互

VBScript可以通过Windows Script Host (WSH)对象与操作系统交互,执行系统级任务。

WScript和CScript对象
  1. ' 检查脚本宿主
  2. If IsObject(WScript) Then
  3.     MsgBox "当前运行在WScript.exe环境中(Windows GUI)"
  4. Else
  5.     MsgBox "当前运行在CScript.exe环境中(命令行)"
  6. End If
  7. ' 使用WScript对象
  8. If IsObject(WScript) Then
  9.     ' 获取脚本名称和路径
  10.     MsgBox "脚本名称: " & WScript.ScriptName
  11.     MsgBox "脚本完整路径: " & WScript.ScriptFullName
  12.    
  13.     ' 获取参数
  14.     If WScript.Arguments.Count > 0 Then
  15.         Dim args, i
  16.         args = ""
  17.         For i = 0 To WScript.Arguments.Count - 1
  18.             args = args & "参数 " & i & ": " & WScript.Arguments(i) & vbCrLf
  19.         Next
  20.         MsgBox "脚本参数:" & vbCrLf & args
  21.     Else
  22.         MsgBox "没有传递任何参数给脚本"
  23.     End If
  24.    
  25.     ' 创建快捷方式
  26.     Dim shell, shortcut, desktopPath
  27.     Set shell = CreateObject("WScript.Shell")
  28.     desktopPath = shell.SpecialFolders("Desktop")
  29.     Set shortcut = shell.CreateShortcut(desktopPath & "\记事本.lnk")
  30.    
  31.     shortcut.TargetPath = "%windir%\notepad.exe"
  32.     shortcut.Description = "打开记事本"
  33.     shortcut.Save
  34.    
  35.     MsgBox "已在桌面创建记事本快捷方式"
  36. End If
复制代码

运行外部程序
  1. ' 创建WScript.Shell对象
  2. Dim shell
  3. Set shell = CreateObject("WScript.Shell")
  4. ' 运行程序并等待完成
  5. Dim command, returnCode
  6. command = "%windir%\notepad.exe"
  7. returnCode = shell.Run(command, 1, True)  ' 1表示激活窗口,True表示等待完成
  8. MsgBox "记事本已关闭,返回代码: " & returnCode
  9. ' 运行程序不等待
  10. command = "%windir%\system32\calc.exe"
  11. shell.Run command, 1, False  ' False表示不等待
  12. MsgBox "计算器已启动(脚本继续执行)"
  13. ' 使用Exec方法运行命令并获取输出
  14. Dim exec, output
  15. command = "cmd /c dir C:"
  16. Set exec = shell.Exec(command)
  17. ' 读取输出
  18. output = ""
  19. Do While exec.Status = 0
  20.     output = output & exec.StdOut.ReadAll()
  21.     WScript.Sleep 100
  22. Loop
  23. ' 显示输出(截取前1000个字符以避免消息框过大)
  24. If Len(output) > 1000 Then
  25.     MsgBox "命令输出(前1000字符):" & vbCrLf & Left(output, 1000) & "..."
  26. Else
  27.     MsgBox "命令输出:" & vbCrLf & output
  28. End If
复制代码

注册表操作
  1. ' 创建WScript.Shell对象
  2. Dim shell
  3. Set shell = CreateObject("WScript.Shell")
  4. ' 读取注册表值
  5. On Error Resume Next
  6. Dim ieVersion
  7. ieVersion = shell.RegRead("HKLM\SOFTWARE\Microsoft\Internet Explorer\Version")
  8. If Err.Number = 0 Then
  9.     MsgBox "Internet Explorer版本: " & ieVersion
  10. Else
  11.     MsgBox "无法读取Internet Explorer版本: " & Err.Description
  12. End If
  13. On Error GoTo 0
  14. ' 写入注册表值
  15. Dim regPath, regValue, regType
  16. regPath = "HKCU\Software\VBScriptTest"
  17. regValue = "TestValue"
  18. regType = "REG_SZ"  ' 字符串类型
  19. ' 创建注册表项
  20. On Error Resume Next
  21. shell.RegWrite regPath & "", "", "REG_SZ"
  22. If Err.Number = 0 Then
  23.     MsgBox "已创建注册表项: " & regPath
  24. Else
  25.     MsgBox "创建注册表项失败: " & Err.Description
  26. End If
  27. On Error GoTo 0
  28. ' 写入注册表值
  29. On Error Resume Next
  30. shell.RegWrite regPath & "" & regValue, "这是一个测试值", regType
  31. If Err.Number = 0 Then
  32.     MsgBox "已写入注册表值: " & regPath & "" & regValue
  33. Else
  34.     MsgBox "写入注册表值失败: " & Err.Description
  35. End If
  36. On Error GoTo 0
  37. ' 读取刚写入的值
  38. On Error Resume Next
  39. Dim readValue
  40. readValue = shell.RegRead(regPath & "" & regValue)
  41. If Err.Number = 0 Then
  42.     MsgBox "读取的注册表值: " & readValue
  43. Else
  44.     MsgBox "读取注册表值失败: " & Err.Description
  45. End If
  46. On Error GoTo 0
  47. ' 删除注册表值
  48. On Error Resume Next
  49. shell.RegDelete regPath & "" & regValue
  50. If Err.Number = 0 Then
  51.     MsgBox "已删除注册表值: " & regPath & "" & regValue
  52. Else
  53.     MsgBox "删除注册表值失败: " & Err.Description
  54. End If
  55. On Error GoTo 0
  56. ' 删除注册表项
  57. On Error Resume Next
  58. shell.RegDelete regPath & ""
  59. If Err.Number = 0 Then
  60.     MsgBox "已删除注册表项: " & regPath
  61. Else
  62.     MsgBox "删除注册表项失败: " & Err.Description
  63. End If
  64. On Error GoTo 0
复制代码

系统信息获取
  1. ' 获取操作系统信息
  2. Dim shell, osInfo
  3. Set shell = CreateObject("WScript.Shell")
  4. osInfo = "操作系统信息:" & vbCrLf & _
  5.          "计算机名: " & shell.ExpandEnvironmentStrings("%COMPUTERNAME%") & vbCrLf & _
  6.          "用户名: " & shell.ExpandEnvironmentStrings("%USERNAME%") & vbCrLf & _
  7.          "系统目录: " & shell.ExpandEnvironmentStrings("%WINDIR%") & vbCrLf & _
  8.          "临时目录: " & shell.ExpandEnvironmentStrings("%TEMP%") & vbCrLf & _
  9.          "程序文件目录: " & shell.ExpandEnvironmentStrings("%ProgramFiles%")
  10. MsgBox osInfo
  11. ' 使用WMI获取更详细的系统信息
  12. Dim wmi, items, item
  13. Set wmi = GetObject("winmgmts:\\.\root\cimv2")
  14. ' 获取操作系统信息
  15. Set items = wmi.ExecQuery("Select * from Win32_OperatingSystem")
  16. For Each item In items
  17.     osInfo = "详细操作系统信息:" & vbCrLf & _
  18.              "名称: " & item.Caption & vbCrLf & _
  19.              "版本: " & item.Version & vbCrLf & _
  20.              "制造商: " & item.Manufacturer & vbCrLf & _
  21.              "安装日期: " & item.InstallDate & vbCrLf & _
  22.              "上次启动时间: " & item.LastBootUpTime & vbCrLf & _
  23.              "本地日期时间: " & item.LocalDateTime & vbCrLf & _
  24.              "序列号: " & item.SerialNumber & vbCrLf & _
  25.              "注册用户: " & item.RegisteredUser & vbCrLf & _
  26.              "组织: " & item.Organization
  27.    
  28.     MsgBox osInfo
  29.     Exit For
  30. Next
  31. ' 获取计算机系统信息
  32. Set items = wmi.ExecQuery("Select * from Win32_ComputerSystem")
  33. For Each item In items
  34.     Dim sysInfo
  35.     sysInfo = "计算机系统信息:" & vbCrLf & _
  36.               "名称: " & item.Name & vbCrLf & _
  37.               "制造商: " & item.Manufacturer & vbCrLf & _
  38.               "型号: " & item.Model & vbCrLf & _
  39.               "系统类型: " & item.SystemType & vbCrLf & _
  40.               "处理器数量: " & item.NumberOfProcessors & vbCrLf & _
  41.               "总物理内存: " & Round(item.TotalPhysicalMemory / 1024 / 1024, 2) & " MB"
  42.    
  43.     MsgBox sysInfo
  44.     Exit For
  45. Next
  46. ' 获取处理器信息
  47. Set items = wmi.ExecQuery("Select * from Win32_Processor")
  48. For Each item In items
  49.     Dim cpuInfo
  50.     cpuInfo = "处理器信息:" & vbCrLf & _
  51.               "名称: " & item.Name & vbCrLf & _
  52.               "制造商: " & item.Manufacturer & vbCrLf & _
  53.               "最大时钟速度: " & item.MaxClockSpeed & " MHz" & vbCrLf & _
  54.               "当前时钟速度: " & item.CurrentClockSpeed & " MHz" & vbCrLf & _
  55.               "核心数: " & item.NumberOfCores & vbCrLf & _
  56.               "逻辑处理器数: " & item.NumberOfLogicalProcessors
  57.    
  58.     MsgBox cpuInfo
  59.     Exit For
  60. Next
复制代码

实际应用案例

自动备份文件
  1. ' 自动备份文件脚本
  2. Option Explicit
  3. ' 配置部分
  4. Dim sourceFolder, backupFolder, logFile
  5. sourceFolder = "C:\ImportantFiles"  ' 要备份的源文件夹
  6. backupFolder = "D:\Backups"         ' 备份目标文件夹
  7. logFile = "D:\Backups\backup_log.txt"  ' 日志文件
  8. ' 创建文件系统对象
  9. Dim fso
  10. Set fso = CreateObject("Scripting.FileSystemObject")
  11. ' 创建日志函数
  12. Sub LogMessage(message)
  13.     Dim logStream
  14.     Set logStream = fso.OpenTextFile(logFile, 8, True)  ' 8 = 追加模式
  15.     logStream.WriteLine Now() & " - " & message
  16.     logStream.Close
  17. End Sub
  18. ' 主程序
  19. On Error Resume Next
  20. ' 检查源文件夹是否存在
  21. If Not fso.FolderExists(sourceFolder) Then
  22.     LogMessage "错误: 源文件夹不存在 - " & sourceFolder
  23.     MsgBox "错误: 源文件夹不存在 - " & sourceFolder, vbCritical
  24.     WScript.Quit(1)
  25. End If
  26. ' 创建备份文件夹(如果不存在)
  27. If Not fso.FolderExists(backupFolder) Then
  28.     fso.CreateFolder backupFolder
  29.     LogMessage "创建备份文件夹 - " & backupFolder
  30. End If
  31. ' 创建带日期的子文件夹
  32. Dim dateFolder
  33. dateFolder = backupFolder & "\Backup_" & Year(Now()) & Right("0" & Month(Now()), 2) & Right("0" & Day(Now()), 2)
  34. If Not fso.FolderExists(dateFolder) Then
  35.     fso.CreateFolder dateFolder
  36.     LogMessage "创建日期备份文件夹 - " & dateFolder
  37. End If
  38. ' 复制文件
  39. Dim sourceFolderObj, file, filesCopied, filesSkipped
  40. Set sourceFolderObj = fso.GetFolder(sourceFolder)
  41. filesCopied = 0
  42. filesSkipped = 0
  43. For Each file In sourceFolderObj.Files
  44.     Dim destFile
  45.     destFile = dateFolder & "" & file.Name
  46.    
  47.     ' 检查文件是否已存在
  48.     If fso.FileExists(destFile) Then
  49.         ' 比较文件修改时间
  50.         Dim destFileObj
  51.         Set destFileObj = fso.GetFile(destFile)
  52.         
  53.         If file.DateLastModified > destFileObj.DateLastModified Then
  54.             ' 源文件更新,覆盖目标文件
  55.             fso.CopyFile file.Path, destFile, True
  56.             LogMessage "更新文件 - " & file.Name
  57.             filesCopied = filesCopied + 1
  58.         Else
  59.             ' 目标文件更新或相同,跳过
  60.             LogMessage "跳过文件(未更改) - " & file.Name
  61.             filesSkipped = filesSkipped + 1
  62.         End If
  63.     Else
  64.         ' 文件不存在,复制
  65.         fso.CopyFile file.Path, destFile
  66.         LogMessage "复制新文件 - " & file.Name
  67.         filesCopied = filesCopied + 1
  68.     End If
  69. Next
  70. ' 递归复制子文件夹
  71. Sub CopySubFolders(sourceFolder, destFolder)
  72.     Dim subFolder, subDestFolder
  73.    
  74.     For Each subFolder In sourceFolder.SubFolders
  75.         subDestFolder = destFolder & "" & subFolder.Name
  76.         
  77.         ' 创建目标子文件夹
  78.         If Not fso.FolderExists(subDestFolder) Then
  79.             fso.CreateFolder subDestFolder
  80.             LogMessage "创建子文件夹 - " & subDestFolder
  81.         End If
  82.         
  83.         ' 复制子文件夹中的文件
  84.         Dim file
  85.         For Each file In subFolder.Files
  86.             Dim destFile
  87.             destFile = subDestFolder & "" & file.Name
  88.             
  89.             ' 检查文件是否已存在
  90.             If fso.FileExists(destFile) Then
  91.                 ' 比较文件修改时间
  92.                 Dim destFileObj
  93.                 Set destFileObj = fso.GetFile(destFile)
  94.                
  95.                 If file.DateLastModified > destFileObj.DateLastModified Then
  96.                     ' 源文件更新,覆盖目标文件
  97.                     fso.CopyFile file.Path, destFile, True
  98.                     LogMessage "更新文件 - " & subFolder.Name & "" & file.Name
  99.                     filesCopied = filesCopied + 1
  100.                 Else
  101.                     ' 目标文件更新或相同,跳过
  102.                     LogMessage "跳过文件(未更改) - " & subFolder.Name & "" & file.Name
  103.                     filesSkipped = filesSkipped + 1
  104.                 End If
  105.             Else
  106.                 ' 文件不存在,复制
  107.                 fso.CopyFile file.Path, destFile
  108.                 LogMessage "复制新文件 - " & subFolder.Name & "" & file.Name
  109.                 filesCopied = filesCopied + 1
  110.             End If
  111.         Next
  112.         
  113.         ' 递归处理子文件夹
  114.         CopySubFolders subFolder, subDestFolder
  115.     Next
  116. End Sub
  117. ' 调用递归函数复制子文件夹
  118. CopySubFolders sourceFolderObj, dateFolder
  119. ' 完成消息
  120. Dim summary
  121. summary = "备份完成!" & vbCrLf & _
  122.           "源文件夹: " & sourceFolder & vbCrLf & _
  123.           "目标文件夹: " & dateFolder & vbCrLf & _
  124.           "复制文件数: " & filesCopied & vbCrLf & _
  125.           "跳过文件数: " & filesSkipped
  126. MsgBox summary, vbInformation
  127. LogMessage summary
  128. ' 清理对象
  129. Set fso = Nothing
  130. Set sourceFolderObj = Nothing
  131. ' 检查错误
  132. If Err.Number <> 0 Then
  133.     LogMessage "错误: " & Err.Description & " (错误号: " & Err.Number & ")"
  134.     MsgBox "发生错误: " & Err.Description & " (错误号: " & Err.Number & ")", vbCritical
  135. End If
  136. On Error GoTo 0
复制代码

批量重命名文件
  1. ' 批量重命名文件脚本
  2. Option Explicit
  3. ' 配置部分
  4. Dim targetFolder, filePrefix, startNumber, padZero, logFile
  5. targetFolder = "C:\Temp\RenameTest"  ' 目标文件夹
  6. filePrefix = "IMG_"                   ' 文件前缀
  7. startNumber = 1                       ' 起始编号
  8. padZero = 4                           ' 编号位数(不足补零)
  9. logFile = "C:\Temp\rename_log.txt"    ' 日志文件
  10. ' 创建文件系统对象
  11. Dim fso
  12. Set fso = CreateObject("Scripting.FileSystemObject")
  13. ' 创建日志函数
  14. Sub LogMessage(message)
  15.     Dim logStream
  16.     Set logStream = fso.OpenTextFile(logFile, 8, True)  ' 8 = 追加模式
  17.     logStream.WriteLine Now() & " - " & message
  18.     logStream.Close
  19. End Sub
  20. ' 格式化编号函数
  21. Function FormatNumber(number, digits)
  22.     Dim result, i
  23.     result = CStr(number)
  24.    
  25.     ' 补零
  26.     For i = Len(result) To digits - 1
  27.         result = "0" & result
  28.     Next
  29.    
  30.     FormatNumber = result
  31. End Function
  32. ' 主程序
  33. On Error Resume Next
  34. ' 检查目标文件夹是否存在
  35. If Not fso.FolderExists(targetFolder) Then
  36.     LogMessage "错误: 目标文件夹不存在 - " & targetFolder
  37.     MsgBox "错误: 目标文件夹不存在 - " & targetFolder, vbCritical
  38.     WScript.Quit(1)
  39. End If
  40. ' 获取文件夹对象
  41. Dim folderObj
  42. Set folderObj = fso.GetFolder(targetFolder)
  43. ' 显示确认信息
  44. Dim confirmMsg
  45. confirmMsg = "将重命名文件夹中的所有文件:" & vbCrLf & _
  46.              "文件夹: " & targetFolder & vbCrLf & _
  47.              "前缀: " & filePrefix & vbCrLf & _
  48.              "起始编号: " & startNumber & vbCrLf & _
  49.              "编号位数: " & padZero & vbCrLf & _
  50.              vbCrLf & "确定要继续吗?"
  51. If MsgBox(confirmMsg, vbQuestion + vbYesNo, "确认重命名") <> vbYes Then
  52.     LogMessage "用户取消了操作"
  53.     WScript.Quit(0)
  54. End If
  55. ' 获取文件列表并按修改时间排序
  56. Dim files(), fileCount, file
  57. fileCount = 0
  58. ' 计算文件数量
  59. For Each file In folderObj.Files
  60.     fileCount = fileCount + 1
  61. Next
  62. ' 调整数组大小
  63. ReDim files(fileCount - 1)
  64. ' 填充数组
  65. Dim index
  66. index = 0
  67. For Each file In folderObj.Files
  68.     Set files(index) = file
  69.     index = index + 1
  70. Next
  71. ' 简单的冒泡排序(按修改时间)
  72. Dim i, j, temp
  73. For i = 0 To UBound(files) - 1
  74.     For j = i + 1 To UBound(files)
  75.         If files(i).DateLastModified > files(j).DateLastModified Then
  76.             Set temp = files(j)
  77.             Set files(j) = files(i)
  78.             Set files(i) = temp
  79.         End If
  80.     Next
  81. Next
  82. ' 重命名文件
  83. Dim currentNumber, renamedCount, skippedCount
  84. currentNumber = startNumber
  85. renamedCount = 0
  86. skippedCount = 0
  87. For i = 0 To UBound(files)
  88.     Dim oldName, newName, extension
  89.     oldName = files(i).Name
  90.    
  91.     ' 获取文件扩展名
  92.     extension = ""
  93.     If InStr(oldName, ".") > 0 Then
  94.         extension = Mid(oldName, InStrRev(oldName, "."))
  95.     End If
  96.    
  97.     ' 构建新文件名
  98.     newName = filePrefix & FormatNumber(currentNumber, padZero) & extension
  99.    
  100.     ' 检查新文件名是否已存在
  101.     If fso.FileExists(targetFolder & "" & newName) Then
  102.         LogMessage "跳过文件(目标文件名已存在): " & oldName & " -> " & newName
  103.         skippedCount = skippedCount + 1
  104.     Else
  105.         ' 重命名文件
  106.         files(i).Name = newName
  107.         LogMessage "重命名文件: " & oldName & " -> " & newName
  108.         renamedCount = renamedCount + 1
  109.         currentNumber = currentNumber + 1
  110.     End If
  111. Next
  112. ' 完成消息
  113. Dim summary
  114. summary = "重命名完成!" & vbCrLf & _
  115.           "文件夹: " & targetFolder & vbCrLf & _
  116.           "重命名文件数: " & renamedCount & vbCrLf & _
  117.           "跳过文件数: " & skippedCount
  118. MsgBox summary, vbInformation
  119. LogMessage summary
  120. ' 清理对象
  121. Set fso = Nothing
  122. Set folderObj = Nothing
  123. Erase files
  124. ' 检查错误
  125. If Err.Number <> 0 Then
  126.     LogMessage "错误: " & Err.Description & " (错误号: " & Err.Number & ")"
  127.     MsgBox "发生错误: " & Err.Description & " (错误号: " & Err.Number & ")", vbCritical
  128. End If
  129. On Error GoTo 0
复制代码

系统信息收集工具
  1. ' 系统信息收集工具
  2. Option Explicit
  3. ' 配置部分
  4. Dim outputFile
  5. outputFile = "C:\Temp\SystemInfo_" & Year(Now()) & Right("0" & Month(Now()), 2) & Right("0" & Day(Now()), 2) & ".html"
  6. ' 创建文件系统对象
  7. Dim fso
  8. Set fso = CreateObject("Scripting.FileSystemObject")
  9. ' 创建WScript.Shell对象
  10. Dim shell
  11. Set shell = CreateObject("WScript.Shell")
  12. ' 创建WMI对象
  13. Dim wmi
  14. Set wmi = GetObject("winmgmts:\\.\root\cimv2")
  15. ' 创建HTML报告
  16. Sub CreateHTMLReport()
  17.     Dim htmlFile, htmlContent
  18.    
  19.     ' 创建输出文件夹(如果不存在)
  20.     Dim outputFolder
  21.     outputFolder = fso.GetParentFolderName(outputFile)
  22.    
  23.     If Not fso.FolderExists(outputFolder) Then
  24.         fso.CreateFolder outputFolder
  25.     End If
  26.    
  27.     ' 创建HTML文件
  28.     Set htmlFile = fso.CreateTextFile(outputFile, True)
  29.    
  30.     ' HTML头部
  31.     htmlContent = "<!DOCTYPE html>" & vbCrLf & _
  32.                   "<html>" & vbCrLf & _
  33.                   "<head>" & vbCrLf & _
  34.                   "    <title>系统信息报告</title>" & vbCrLf & _
  35.                   "    <meta charset=""utf-8"">" & vbCrLf & _
  36.                   "    <style>" & vbCrLf & _
  37.                   "        body { font-family: Arial, sans-serif; margin: 20px; }" & vbCrLf & _
  38.                   "        h1, h2, h3 { color: #0066cc; }" & vbCrLf & _
  39.                   "        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }" & vbCrLf & _
  40.                   "        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }" & vbCrLf & _
  41.                   "        th { background-color: #f2f2f2; }" & vbCrLf & _
  42.                   "        tr:nth-child(even) { background-color: #f9f9f9; }" & vbCrLf & _
  43.                   "        .timestamp { color: #666; font-size: 0.9em; }" & vbCrLf & _
  44.                   "    </style>" & vbCrLf & _
  45.                   "</head>" & vbCrLf & _
  46.                   "<body>" & vbCrLf & _
  47.                   "    <h1>系统信息报告</h1>" & vbCrLf & _
  48.                   "    <p class=""timestamp"">生成时间: " & Now() & "</p>" & vbCrLf & _
  49.                   "    <hr>" & vbCrLf
  50.    
  51.     ' 添加基本信息
  52.     htmlContent = htmlContent & GetBasicInfo()
  53.    
  54.     ' 添加操作系统信息
  55.     htmlContent = htmlContent & GetOSInfo()
  56.    
  57.     ' 添加计算机系统信息
  58.     htmlContent = htmlContent & GetComputerSystemInfo()
  59.    
  60.     ' 添加处理器信息
  61.     htmlContent = htmlContent & GetProcessorInfo()
  62.    
  63.     ' 添加内存信息
  64.     htmlContent = htmlContent & GetMemoryInfo()
  65.    
  66.     ' 添加磁盘信息
  67.     htmlContent = htmlContent & GetDiskInfo()
  68.    
  69.     ' 添加网络适配器信息
  70.     htmlContent = htmlContent & GetNetworkAdapterInfo()
  71.    
  72.     ' 添加软件信息
  73.     htmlContent = htmlContent & GetSoftwareInfo()
  74.    
  75.     ' 添加服务信息
  76.     htmlContent = htmlContent & GetServiceInfo()
  77.    
  78.     ' 添加进程信息
  79.     htmlContent = htmlContent & GetProcessInfo()
  80.    
  81.     ' HTML尾部
  82.     htmlContent = htmlContent & "</body>" & vbCrLf & "</html>"
  83.    
  84.     ' 写入HTML文件
  85.     htmlFile.Write htmlContent
  86.     htmlFile.Close
  87.    
  88.     ' 显示完成消息
  89.     MsgBox "系统信息报告已生成: " & outputFile, vbInformation
  90.    
  91.     ' 打开报告
  92.     shell.Run outputFile
  93. End Sub
  94. ' 获取基本信息
  95. Function GetBasicInfo()
  96.     Dim html, computerName, userName, domain
  97.    
  98.     computerName = shell.ExpandEnvironmentStrings("%COMPUTERNAME%")
  99.     userName = shell.ExpandEnvironmentStrings("%USERNAME%")
  100.     domain = shell.ExpandEnvironmentStrings("%USERDOMAIN%")
  101.    
  102.     html = "<h2>基本信息</h2>" & vbCrLf & _
  103.            "<table>" & vbCrLf & _
  104.            "    <tr><th>项目</th><th>值</th></tr>" & vbCrLf & _
  105.            "    <tr><td>计算机名</td><td>" & computerName & "</td></tr>" & vbCrLf & _
  106.            "    <tr><td>用户名</td><td>" & userName & "</td></tr>" & vbCrLf & _
  107.            "    <tr><td>域</td><td>" & domain & "</td></tr>" & vbCrLf & _
  108.            "</table>" & vbCrLf
  109.    
  110.     GetBasicInfo = html
  111. End Function
  112. ' 获取操作系统信息
  113. Function GetOSInfo()
  114.     Dim html, items, item
  115.    
  116.     Set items = wmi.ExecQuery("Select * from Win32_OperatingSystem")
  117.    
  118.     html = "<h2>操作系统信息</h2>" & vbCrLf & _
  119.            "<table>" & vbCrLf & _
  120.            "    <tr><th>属性</th><th>值</th></tr>" & vbCrLf
  121.    
  122.     For Each item In items
  123.         html = html & "    <tr><td>名称</td><td>" & item.Caption & "</td></tr>" & vbCrLf & _
  124.                      "    <tr><td>版本</td><td>" & item.Version & "</td></tr>" & vbCrLf & _
  125.                      "    <tr><td>制造商</td><td>" & item.Manufacturer & "</td></tr>" & vbCrLf & _
  126.                      "    <tr><td>系统目录</td><td>" & item.WindowsDirectory & "</td></tr>" & vbCrLf & _
  127.                      "    <tr><td>本地日期时间</td><td>" & item.LocalDateTime & "</td></tr>" & _
  128.                      "    <tr><td>上次启动时间</td><td>" & item.LastBootUpTime & "</td></tr>" & vbCrLf & _
  129.                      "    <tr><td>序列号</td><td>" & item.SerialNumber & "</td></tr>" & vbCrLf
  130.         Exit For
  131.     Next
  132.    
  133.     html = html & "</table>" & vbCrLf
  134.    
  135.     GetOSInfo = html
  136. End Function
  137. ' 获取计算机系统信息
  138. Function GetComputerSystemInfo()
  139.     Dim html, items, item
  140.    
  141.     Set items = wmi.ExecQuery("Select * from Win32_ComputerSystem")
  142.    
  143.     html = "<h2>计算机系统信息</h2>" & vbCrLf & _
  144.            "<table>" & vbCrLf & _
  145.            "    <tr><th>属性</th><th>值</th></tr>" & vbCrLf
  146.    
  147.     For Each item In items
  148.         html = html & "    <tr><td>制造商</td><td>" & item.Manufacturer & "</td></tr>" & vbCrLf & _
  149.                      "    <tr><td>型号</td><td>" & item.Model & "</td></tr>" & vbCrLf & _
  150.                      "    <tr><td>系统类型</td><td>" & item.SystemType & "</td></tr>" & vbCrLf & _
  151.                      "    <tr><td>处理器数量</td><td>" & item.NumberOfProcessors & "</td></tr>" & vbCrLf & _
  152.                      "    <tr><td>总物理内存</td><td>" & Round(item.TotalPhysicalMemory / 1024 / 1024, 2) & " MB</td></tr>" & vbCrLf
  153.         Exit For
  154.     Next
  155.    
  156.     html = html & "</table>" & vbCrLf
  157.    
  158.     GetComputerSystemInfo = html
  159. End Function
  160. ' 获取处理器信息
  161. Function GetProcessorInfo()
  162.     Dim html, items, item
  163.    
  164.     Set items = wmi.ExecQuery("Select * from Win32_Processor")
  165.    
  166.     html = "<h2>处理器信息</h2>" & vbCrLf & _
  167.            "<table>" & vbCrLf & _
  168.            "    <tr><th>属性</th><th>值</th></tr>" & vbCrLf
  169.    
  170.     For Each item In items
  171.         html = html & "    <tr><td>名称</td><td>" & item.Name & "</td></tr>" & vbCrLf & _
  172.                      "    <tr><td>制造商</td><td>" & item.Manufacturer & "</td></tr>" & vbCrLf & _
  173.                      "    <tr><td>最大时钟速度</td><td>" & item.MaxClockSpeed & " MHz</td></tr>" & vbCrLf & _
  174.                      "    <tr><td>当前时钟速度</td><td>" & item.CurrentClockSpeed & " MHz</td></tr>" & vbCrLf & _
  175.                      "    <tr><td>核心数</td><td>" & item.NumberOfCores & "</td></tr>" & vbCrLf & _
  176.                      "    <tr><td>逻辑处理器数</td><td>" & item.NumberOfLogicalProcessors & "</td></tr>" & vbCrLf
  177.     Next
  178.    
  179.     html = html & "</table>" & vbCrLf
  180.    
  181.     GetProcessorInfo = html
  182. End Function
  183. ' 获取内存信息
  184. Function GetMemoryInfo()
  185.     Dim html, items, item
  186.    
  187.     Set items = wmi.ExecQuery("Select * from Win32_PhysicalMemory")
  188.    
  189.     html = "<h2>内存信息</h2>" & vbCrLf & _
  190.            "<table>" & vbCrLf & _
  191.            "    <tr><th>属性</th><th>值</th></tr>" & vbCrLf
  192.    
  193.     Dim totalCapacity
  194.     totalCapacity = 0
  195.    
  196.     For Each item In items
  197.         Dim capacity
  198.         capacity = item.Capacity / 1024 / 1024  ' 转换为MB
  199.         totalCapacity = totalCapacity + capacity
  200.         
  201.         html = html & "    <tr><td>内存条 " & item.DeviceLocator & "</td><td>" & Round(capacity, 2) & " MB</td></tr>" & vbCrLf
  202.     Next
  203.    
  204.     html = html & "    <tr><td><strong>总内存</strong></td><td><strong>" & Round(totalCapacity, 2) & " MB</strong></td></tr>" & vbCrLf
  205.     html = html & "</table>" & vbCrLf
  206.    
  207.     GetMemoryInfo = html
  208. End Function
  209. ' 获取磁盘信息
  210. Function GetDiskInfo()
  211.     Dim html, items, item
  212.    
  213.     Set items = wmi.ExecQuery("Select * from Win32_LogicalDisk Where DriveType=3")
  214.    
  215.     html = "<h2>磁盘信息</h2>" & vbCrLf & _
  216.            "<table>" & vbCrLf & _
  217.            "    <tr><th>驱动器</th><th>文件系统</th><th>总大小</th><th>可用空间</th><th>使用率</th></tr>" & vbCrLf
  218.    
  219.     For Each item In items
  220.         Dim totalSize, freeSpace, usedSpace, usagePercent
  221.         
  222.         totalSize = item.Size / 1024 / 1024 / 1024  ' 转换为GB
  223.         freeSpace = item.FreeSpace / 1024 / 1024 / 1024  ' 转换为GB
  224.         usedSpace = totalSize - freeSpace
  225.         usagePercent = Round((usedSpace / totalSize) * 100, 2)
  226.         
  227.         html = html & "    <tr><td>" & item.DeviceID & "</td><td>" & item.FileSystem & "</td><td>" & _
  228.                      Round(totalSize, 2) & " GB</td><td>" & Round(freeSpace, 2) & " GB</td><td>" & _
  229.                      usagePercent & "%</td></tr>" & vbCrLf
  230.     Next
  231.    
  232.     html = html & "</table>" & vbCrLf
  233.    
  234.     GetDiskInfo = html
  235. End Function
  236. ' 获取网络适配器信息
  237. Function GetNetworkAdapterInfo()
  238.     Dim html, items, item
  239.    
  240.     Set items = wmi.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=True")
  241.    
  242.     html = "<h2>网络适配器信息</h2>" & vbCrLf & _
  243.            "<table>" & vbCrLf & _
  244.            "    <tr><th>属性</th><th>值</th></tr>" & vbCrLf
  245.    
  246.     For Each item In items
  247.         Dim ipAddresses, macAddress
  248.         
  249.         ' 获取IP地址
  250.         ipAddresses = Join(item.IPAddress, ", ")
  251.         
  252.         ' 获取MAC地址
  253.         macAddress = item.MACAddress
  254.         
  255.         html = html & "    <tr><td>描述</td><td>" & item.Description & "</td></tr>" & vbCrLf & _
  256.                      "    <tr><td>MAC地址</td><td>" & macAddress & "</td></tr>" & vbCrLf & _
  257.                      "    <tr><td>IP地址</td><td>" & ipAddresses & "</td></tr>" & vbCrLf & _
  258.                      "    <tr><td>子网掩码</td><td>" & Join(item.IPSubnet, ", ") & "</td></tr>" & vbCrLf & _
  259.                      "    <tr><td>默认网关</td><td>" & Join(item.DefaultIPGateway, ", ") & "</td></tr>" & vbCrLf & _
  260.                      "    <tr><td>DNS服务器</td><td>" & Join(item.DNSServerSearchOrder, ", ") & "</td></tr>" & vbCrLf & _
  261.                      "    <tr><td>DHCP启用</td><td>" & item.DHCPEnabled & "</td></tr>" & vbCrLf
  262.     Next
  263.    
  264.     html = html & "</table>" & vbCrLf
  265.    
  266.     GetNetworkAdapterInfo = html
  267. End Function
  268. ' 获取软件信息
  269. Function GetSoftwareInfo()
  270.     Dim html, items, item
  271.    
  272.     Set items = wmi.ExecQuery("Select * from Win32_Product")
  273.    
  274.     html = "<h2>已安装软件</h2>" & vbCrLf & _
  275.            "<table>" & vbCrLf & _
  276.            "    <tr><th>名称</th><th>版本</th><th>供应商</th><th>安装日期</th></tr>" & vbCrLf
  277.    
  278.     For Each item In items
  279.         Dim installDate
  280.         installDate = item.InstallDate
  281.         
  282.         ' 格式化日期 (YYYYMMDD -> YYYY-MM-DD)
  283.         If Len(installDate) >= 8 Then
  284.             installDate = Left(installDate, 4) & "-" & Mid(installDate, 5, 2) & "-" & Mid(installDate, 7, 2)
  285.         Else
  286.             installDate = "未知"
  287.         End If
  288.         
  289.         html = html & "    <tr><td>" & item.Name & "</td><td>" & item.Version & "</td><td>" & _
  290.                      item.Vendor & "</td><td>" & installDate & "</td></tr>" & vbCrLf
  291.     Next
  292.    
  293.     html = html & "</table>" & vbCrLf
  294.    
  295.     GetSoftwareInfo = html
  296. End Function
  297. ' 获取服务信息
  298. Function GetServiceInfo()
  299.     Dim html, items, item
  300.    
  301.     Set items = wmi.ExecQuery("Select * from Win32_Service Where State='Running'")
  302.    
  303.     html = "<h2>运行中的服务</h2>" & vbCrLf & _
  304.            "<table>" & vbCrLf & _
  305.            "    <tr><th>名称</th><th>显示名称</th><th>状态</th><th>启动模式</th><th>进程ID</th></tr>" & vbCrLf
  306.    
  307.     For Each item In items
  308.         html = html & "    <tr><td>" & item.Name & "</td><td>" & item.DisplayName & "</td><td>" & _
  309.                      item.State & "</td><td>" & item.StartMode & "</td><td>" & item.ProcessId & "</td></tr>" & vbCrLf
  310.     Next
  311.    
  312.     html = html & "</table>" & vbCrLf
  313.    
  314.     GetServiceInfo = html
  315. End Function
  316. ' 获取进程信息
  317. Function GetProcessInfo()
  318.     Dim html, items, item
  319.    
  320.     Set items = wmi.ExecQuery("Select * from Win32_Process")
  321.    
  322.     html = "<h2>运行中的进程</h2>" & vbCrLf & _
  323.            "<table>" & vbCrLf & _
  324.            "    <tr><th>名称</th><th>进程ID</th><th>父进程ID</th><th>线程数</th><th>路径</th></tr>" & vbCrLf
  325.    
  326.     For Each item In items
  327.         html = html & "    <tr><td>" & item.Name & "</td><td>" & item.ProcessId & "</td><td>" & _
  328.                      item.ParentProcessId & "</td><td>" & item.ThreadCount & "</td><td>" & _
  329.                      item.ExecutablePath & "</td></tr>" & vbCrLf
  330.     Next
  331.    
  332.     html = html & "</table>" & vbCrLf
  333.    
  334.     GetProcessInfo = html
  335. End Function
  336. ' 主程序
  337. On Error Resume Next
  338. ' 创建HTML报告
  339. CreateHTMLReport()
  340. ' 检查错误
  341. If Err.Number <> 0 Then
  342.     MsgBox "发生错误: " & Err.Description & " (错误号: " & Err.Number & ")", vbCritical
  343. End If
  344. On Error GoTo 0
  345. ' 清理对象
  346. Set fso = Nothing
  347. Set shell = Nothing
  348. Set wmi = Nothing
复制代码

进阶技巧

错误处理

良好的错误处理是编写健壮脚本的关键。VBScript提供了On Error语句来控制错误处理。
  1. ' 基本错误处理示例
  2. Sub DivideNumbers(a, b)
  3.     On Error Resume Next  ' 启用错误处理
  4.    
  5.     Dim result
  6.     result = a / b
  7.    
  8.     If Err.Number <> 0 Then
  9.         MsgBox "错误: " & Err.Description & " (错误号: " & Err.Number & ")"
  10.     Else
  11.         MsgBox "结果: " & result
  12.     End If
  13.    
  14.     On Error GoTo 0  ' 禁用错误处理
  15. End Sub
  16. DivideNumbers 10, 2  ' 正常情况
  17. DivideNumbers 10, 0  ' 错误情况(除以零)
  18. ' 更复杂的错误处理
  19. Sub ProcessFile(filePath)
  20.     On Error Resume Next
  21.    
  22.     Dim fso, file, content
  23.     Set fso = CreateObject("Scripting.FileSystemObject")
  24.    
  25.     ' 检查文件是否存在
  26.     If Not fso.FileExists(filePath) Then
  27.         MsgBox "错误: 文件不存在 - " & filePath
  28.         Exit Sub
  29.     End If
  30.    
  31.     ' 尝试打开文件
  32.     Set file = fso.OpenTextFile(filePath, 1)  ' 1 = 只读模式
  33.    
  34.     If Err.Number <> 0 Then
  35.         MsgBox "错误: 无法打开文件 - " & Err.Description
  36.         Exit Sub
  37.     End If
  38.    
  39.     ' 读取文件内容
  40.     content = file.ReadAll
  41.    
  42.     If Err.Number <> 0 Then
  43.         MsgBox "错误: 无法读取文件 - " & Err.Description
  44.         file.Close
  45.         Exit Sub
  46.     End If
  47.    
  48.     ' 关闭文件
  49.     file.Close
  50.    
  51.     ' 处理内容(这里只是显示长度)
  52.     MsgBox "文件内容长度: " & Len(content) & " 字符"
  53.    
  54.     On Error GoTo 0
  55. End Sub
  56. ProcessFile "C:\Temp\test.txt"  ' 替换为实际存在的文件路径
  57. ProcessFile "C:\Temp\nonexistent.txt"  ' 不存在的文件
  58. ' 使用Err对象的Raise方法自定义错误
  59. Sub ValidateAge(age)
  60.     If age < 0 Then
  61.         Err.Raise vbObjectError + 1, "ValidateAge", "年龄不能为负数"
  62.     ElseIf age > 150 Then
  63.         Err.Raise vbObjectError + 2, "ValidateAge", "年龄不能超过150岁"
  64.     End If
  65.    
  66.     MsgBox "年龄验证通过: " & age
  67. End Sub
  68. Sub TestValidateAge()
  69.     On Error Resume Next
  70.    
  71.     ValidateAge 25  ' 有效年龄
  72.    
  73.     If Err.Number <> 0 Then
  74.         MsgBox "错误: " & Err.Description
  75.         Err.Clear
  76.     End If
  77.    
  78.     ValidateAge -5  ' 无效年龄
  79.    
  80.     If Err.Number <> 0 Then
  81.         MsgBox "错误: " & Err.Description
  82.         Err.Clear
  83.     End If
  84.    
  85.     ValidateAge 200  ' 无效年龄
  86.    
  87.     If Err.Number <> 0 Then
  88.         MsgBox "错误: " & Err.Description
  89.         Err.Clear
  90.     End If
  91.    
  92.     On Error GoTo 0
  93. End Sub
  94. TestValidateAge
复制代码

类和对象

VBScript支持使用Class语句创建自定义对象,这对于组织代码和创建可重用组件非常有用。
  1. ' 定义一个简单的Person类
  2. Class Person
  3.     ' 私有字段
  4.     Private m_Name
  5.     Private m_Age
  6.     Private m_Gender
  7.    
  8.     ' 构造函数
  9.     Private Sub Class_Initialize()
  10.         m_Name = ""
  11.         m_Age = 0
  12.         m_Gender = ""
  13.     End Sub
  14.    
  15.     ' 析构函数
  16.     Private Sub Class_Terminate()
  17.         ' 清理代码
  18.     End Sub
  19.    
  20.     ' 公共属性
  21.     Public Property Get Name
  22.         Name = m_Name
  23.     End Property
  24.    
  25.     Public Property Let Name(value)
  26.         m_Name = value
  27.     End Property
  28.    
  29.     Public Property Get Age
  30.         Age = m_Age
  31.     End Property
  32.    
  33.     Public Property Let Age(value)
  34.         If value >= 0 And value <= 150 Then
  35.             m_Age = value
  36.         Else
  37.             Err.Raise vbObjectError + 1, "Person.Age", "年龄必须在0到150之间"
  38.         End If
  39.     End Property
  40.    
  41.     Public Property Get Gender
  42.         Gender = m_Gender
  43.     End Property
  44.    
  45.     Public Property Let Gender(value)
  46.         m_Gender = value
  47.     End Property
  48.    
  49.     ' 公共方法
  50.     Public Sub Introduce()
  51.         MsgBox "大家好,我叫" & m_Name & ",今年" & m_Age & "岁。"
  52.     End Sub
  53.    
  54.     Public Function IsAdult()
  55.         IsAdult = (m_Age >= 18)
  56.     End Function
  57. End Class
  58. ' 使用Person类
  59. Dim person1, person2
  60. Set person1 = New Person
  61. ' 设置属性
  62. person1.Name = "张三"
  63. person1.Age = 25
  64. person1.Gender = "男"
  65. ' 调用方法
  66. person1.Introduce()
  67. If person1.IsAdult() Then
  68.     MsgBox person1.Name & "是成年人。"
  69. Else
  70.     MsgBox person1.Name & "不是成年人。"
  71. End If
  72. ' 创建另一个Person对象
  73. Set person2 = New Person
  74. person2.Name = "李四"
  75. person2.Age = 16
  76. person2.Gender = "女"
  77. person2.Introduce()
  78. If person2.IsAdult() Then
  79.     MsgBox person2.Name & "是成年人。"
  80. Else
  81.     MsgBox person2.Name & "不是成年人。"
  82. End If
  83. ' 定义一个更复杂的Employee类,继承自Person
  84. Class Employee
  85.     ' 私有字段
  86.     Private m_Person
  87.     Private m_Department
  88.     Private m_Salary
  89.    
  90.     ' 构造函数
  91.     Private Sub Class_Initialize()
  92.         Set m_Person = New Person
  93.         m_Department = ""
  94.         m_Salary = 0
  95.     End Sub
  96.    
  97.     ' 析构函数
  98.     Private Sub Class_Terminate()
  99.         Set m_Person = Nothing
  100.     End Sub
  101.    
  102.     ' 公共属性(委托给Person对象)
  103.     Public Property Get Name
  104.         Name = m_Person.Name
  105.     End Property
  106.    
  107.     Public Property Let Name(value)
  108.         m_Person.Name = value
  109.     End Property
  110.    
  111.     Public Property Get Age
  112.         Age = m_Person.Age
  113.     End Property
  114.    
  115.     Public Property Let Age(value)
  116.         m_Person.Age = value
  117.     End Property
  118.    
  119.     Public Property Get Gender
  120.         Gender = m_Person.Gender
  121.     End Property
  122.    
  123.     Public Property Let Gender(value)
  124.         m_Person.Gender = value
  125.     End Property
  126.    
  127.     ' Employee特有属性
  128.     Public Property Get Department
  129.         Department = m_Department
  130.     End Property
  131.    
  132.     Public Property Let Department(value)
  133.         m_Department = value
  134.     End Property
  135.    
  136.     Public Property Get Salary
  137.         Salary = m_Salary
  138.     End Property
  139.    
  140.     Public Property Let Salary(value)
  141.         If value >= 0 Then
  142.             m_Salary = value
  143.         Else
  144.             Err.Raise vbObjectError + 1, "Employee.Salary", "薪水不能为负数"
  145.         End If
  146.     End Property
  147.    
  148.     ' 公共方法
  149.     Public Sub Introduce()
  150.         m_Person.Introduce()
  151.         MsgBox "我在" & m_Department & "部门工作,月薪为" & m_Salary & "元。"
  152.     End Sub
  153.    
  154.     Public Function GetAnnualSalary()
  155.         GetAnnualSalary = m_Salary * 12
  156.     End Function
  157.    
  158.     Public Sub RaiseSalary(percent)
  159.         If percent > 0 Then
  160.             m_Salary = m_Salary * (1 + percent / 100)
  161.             MsgBox "恭喜!您的薪水已提高" & percent & "%,新月薪为" & m_Salary & "元。"
  162.         Else
  163.             Err.Raise vbObjectError + 2, "Employee.RaiseSalary", "提高百分比必须为正数"
  164.         End If
  165.     End Sub
  166. End Class
  167. ' 使用Employee类
  168. Dim employee
  169. Set employee = New Employee
  170. ' 设置属性
  171. employee.Name = "王五"
  172. employee.Age = 30
  173. employee.Gender = "男"
  174. employee.Department = "技术部"
  175. employee.Salary = 8000
  176. ' 调用方法
  177. employee.Introduce()
  178. MsgBox employee.Name & "的年薪为" & employee.GetAnnualSalary() & "元。"
  179. ' 提高薪水
  180. employee.RaiseSalary(10)
  181. MsgBox employee.Name & "提高后的年薪为" & employee.GetAnnualSalary() & "元。"
复制代码

正则表达式

VBScript通过VBScript.RegExp对象支持正则表达式,这对于文本处理和模式匹配非常有用。
  1. ' 基本正则表达式匹配
  2. Sub TestRegExp()
  3.     Dim regex, match, matches
  4.     Set regex = New RegExp
  5.    
  6.     ' 设置正则表达式模式
  7.     regex.Pattern = "\d+"  ' 匹配一个或多个数字
  8.    
  9.     ' 设置是否区分大小写
  10.     regex.IgnoreCase = True
  11.    
  12.     ' 设置是否全局匹配
  13.     regex.Global = True
  14.    
  15.     ' 测试字符串
  16.     Dim testString
  17.     testString = "电话号码: 123-456-7890, 邮编: 100001"
  18.    
  19.     ' 执行匹配
  20.     Set matches = regex.Execute(testString)
  21.    
  22.     ' 显示匹配结果
  23.     Dim result
  24.     result = "在字符串 """ & testString & """ 中找到以下数字:" & vbCrLf
  25.    
  26.     For Each match In matches
  27.         result = result & "找到: " & match.Value & " (位置: " & match.FirstIndex & ", 长度: " & match.Length & ")" & vbCrLf
  28.     Next
  29.    
  30.     MsgBox result
  31. End Sub
  32. TestRegExp()
  33. ' 验证电子邮件地址
  34. Function IsValidEmail(email)
  35.     Dim regex
  36.     Set regex = New RegExp
  37.    
  38.     ' 电子邮件正则表达式模式
  39.     regex.Pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
  40.    
  41.     ' 执行测试
  42.     IsValidEmail = regex.Test(email)
  43. End Function
  44. ' 测试电子邮件验证
  45. Sub TestEmailValidation()
  46.     Dim emails, email, result
  47.    
  48.     emails = Array("user@example.com", "user.name@example.co.uk", "invalid-email", "@example.com", "user@.com")
  49.    
  50.     result = "电子邮件验证结果:" & vbCrLf
  51.    
  52.     For Each email In emails
  53.         result = result & email & " - " & IIf(IsValidEmail(email), "有效", "无效") & vbCrLf
  54.     Next
  55.    
  56.     MsgBox result
  57. End Sub
  58. ' 辅助函数(VBScript没有内置的IIf函数)
  59. Function IIf(condition, truePart, falsePart)
  60.     If condition Then
  61.         IIf = truePart
  62.     Else
  63.         IIf = falsePart
  64.     End If
  65. End Function
  66. TestEmailValidation()
  67. ' 替换文本
  68. Sub ReplaceText()
  69.     Dim regex, inputText, outputText
  70.    
  71.     Set regex = New RegExp
  72.    
  73.     ' 设置正则表达式模式
  74.     regex.Pattern = "\b(\d{1,2})/(\d{1,2})/(\d{4})\b"  ' 匹配 MM/DD/YYYY 格式的日期
  75.    
  76.     ' 设置全局匹配
  77.     regex.Global = True
  78.    
  79.     ' 输入文本
  80.     inputText = "会议日期: 05/15/2023, 截止日期: 06/30/2023"
  81.    
  82.     ' 替换为 YYYY-MM-DD 格式
  83.     outputText = regex.Replace(inputText, "$3-$1-$2")
  84.    
  85.     MsgBox "原始文本: " & inputText & vbCrLf & _
  86.            "替换后: " & outputText
  87. End Sub
  88. ReplaceText()
  89. ' 提取HTML标签内容
  90. Sub ExtractHTMLTags()
  91.     Dim regex, html, matches, match, result
  92.    
  93.     Set regex = New RegExp
  94.    
  95.     ' 设置正则表达式模式
  96.     regex.Pattern = "<([^>]+)>([^<]*)</\1>"  ' 匹配HTML标签及其内容
  97.    
  98.     ' 设置全局匹配
  99.     regex.Global = True
  100.    
  101.     ' HTML文本
  102.     html = "<div><h1>标题</h1><p>这是一个段落。</p></div>"
  103.    
  104.     ' 执行匹配
  105.     Set matches = regex.Execute(html)
  106.    
  107.     ' 显示匹配结果
  108.     result = "在HTML中找到以下标签:" & vbCrLf
  109.    
  110.     For Each match In matches
  111.         result = result & "标签: " & match.SubMatches(0) & ", 内容: " & match.SubMatches(1) & vbCrLf
  112.     Next
  113.    
  114.     MsgBox result
  115. End Sub
  116. ExtractHTMLTags()
  117. ' 分割字符串
  118. Sub SplitString()
  119.     Dim regex, inputText, result
  120.    
  121.     Set regex = New RegExp
  122.    
  123.     ' 设置正则表达式模式
  124.     regex.Pattern = "\s*,\s*"  ' 匹配逗号及其前后的空白字符
  125.    
  126.     ' 设置全局匹配
  127.     regex.Global = True
  128.    
  129.     ' 输入文本
  130.     inputText = "苹果, 香蕉, 橙子, 葡萄"
  131.    
  132.     ' 分割字符串
  133.     result = Split(regex.Replace(inputText, ","), ",")
  134.    
  135.     ' 显示结果
  136.     Dim output, item
  137.     output = "分割结果:" & vbCrLf
  138.    
  139.     For Each item In result
  140.         output = output & item & vbCrLf
  141.     Next
  142.    
  143.     MsgBox output
  144. End Sub
  145. SplitString()
复制代码

常见问题和解决方案

问题1:脚本运行时出现”权限被拒绝”错误

解决方案:
  1. ' 检查管理员权限并请求提升
  2. Function IsAdmin()
  3.     On Error Resume Next
  4.    
  5.     Dim shell
  6.     Set shell = CreateObject("WScript.Shell")
  7.    
  8.     ' 尝试执行需要管理员权限的操作
  9.     shell.RegRead "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
  10.    
  11.     IsAdmin = (Err.Number = 0)
  12.    
  13.     On Error GoTo 0
  14. End Function
  15. Sub RunAsAdmin()
  16.     If Not IsAdmin() Then
  17.         Dim shell
  18.         Set shell = CreateObject("WScript.Shell")
  19.         
  20.         ' 重新以管理员权限运行脚本
  21.         shell.Run "wscript.exe //e:vbscript """ & WScript.ScriptFullName & """", 0, False
  22.         
  23.         ' 退出当前脚本
  24.         WScript.Quit
  25.     End If
  26. End Sub
  27. ' 在脚本开始处调用
  28. RunAsAdmin()
  29. ' 现在可以执行需要管理员权限的操作
  30. MsgBox "脚本正在以管理员权限运行"
复制代码

问题2:处理包含特殊字符的文件路径

解决方案:
  1. ' 处理包含特殊字符的文件路径
  2. Sub HandleSpecialCharsInPath()
  3.     Dim fso, filePath, file
  4.    
  5.     Set fso = CreateObject("Scripting.FileSystemObject")
  6.    
  7.     ' 包含特殊字符的文件路径
  8.     filePath = "C:\Temp\Special [Chars] & File.txt"
  9.    
  10.     ' 检查文件是否存在
  11.     If fso.FileExists(filePath) Then
  12.         Set file = fso.GetFile(filePath)
  13.         MsgBox "文件存在: " & file.Name & vbCrLf & "大小: " & file.Size & " 字节"
  14.     Else
  15.         ' 创建文件
  16.         Set file = fso.CreateTextFile(filePath, True)
  17.         file.WriteLine "这是一个包含特殊字符的文件"
  18.         file.Close
  19.         
  20.         MsgBox "已创建文件: " & filePath
  21.     End If
  22. End Sub
  23. HandleSpecialCharsInPath()
复制代码

问题3:脚本执行速度慢

解决方案:
  1. ' 优化脚本执行速度
  2. Sub OptimizeScriptPerformance()
  3.     Dim startTime, endTime, fso, folder, file, fileCount
  4.    
  5.     ' 记录开始时间
  6.     startTime = Timer
  7.    
  8.     ' 创建对象(只创建一次)
  9.     Set fso = CreateObject("Scripting.FileSystemObject")
  10.    
  11.     ' 获取文件夹
  12.     Set folder = fso.GetFolder("C:\Windows")
  13.    
  14.     ' 预分配数组大小(如果可能)
  15.     fileCount = folder.Files.Count
  16.     ReDim fileNames(fileCount - 1)
  17.    
  18.     ' 使用For Each循环(比For循环更快)
  19.     Dim i
  20.     i = 0
  21.     For Each file In folder.Files
  22.         fileNames(i) = file.Name
  23.         i = i + 1
  24.     Next
  25.    
  26.     ' 减少与对象的交互
  27.     Dim output
  28.     output = "找到 " & fileCount & " 个文件:" & vbCrLf
  29.    
  30.     ' 使用字符串连接(比多次使用&更快)
  31.     For i = 0 To UBound(fileNames)
  32.         output = output & fileNames(i) & vbCrLf
  33.     Next
  34.    
  35.     ' 记录结束时间
  36.     endTime = Timer
  37.    
  38.     ' 显示结果和执行时间
  39.     MsgBox output & vbCrLf & "执行时间: " & FormatNumber(endTime - startTime, 2) & " 秒"
  40. End Sub
  41. OptimizeScriptPerformance()
复制代码

问题4:处理大文件时的内存问题

解决方案:
  1. ' 处理大文件时避免内存问题
  2. Sub ProcessLargeFile()
  3.     Dim fso, inputFile, outputFile, line, linesProcessed
  4.    
  5.     Set fso = CreateObject("Scripting.FileSystemObject")
  6.    
  7.     ' 输入和输出文件路径
  8.     Dim inputPath, outputPath
  9.     inputPath = "C:\Temp\large_file.txt"
  10.     outputPath = "C:\Temp\processed_file.txt"
  11.    
  12.     ' 检查输入文件是否存在
  13.     If Not fso.FileExists(inputPath) Then
  14.         MsgBox "输入文件不存在: " & inputPath
  15.         Exit Sub
  16.     End If
  17.    
  18.     ' 打开输入文件
  19.     Set inputFile = fso.OpenTextFile(inputPath, 1)  ' 1 = 只读模式
  20.    
  21.     ' 创建输出文件
  22.     Set outputFile = fso.CreateTextFile(outputPath, True)  ' True = 可覆盖
  23.    
  24.     ' 初始化计数器
  25.     linesProcessed = 0
  26.    
  27.     ' 逐行处理文件(避免一次性读取整个文件)
  28.     Do Until inputFile.AtEndOfStream
  29.         line = inputFile.ReadLine
  30.         
  31.         ' 处理行(这里只是简单地将行写入输出文件)
  32.         outputFile.WriteLine "Processed: " & line
  33.         
  34.         ' 更新计数器
  35.         linesProcessed = linesProcessed + 1
  36.         
  37.         ' 每处理1000行显示一次进度
  38.         If linesProcessed Mod 1000 = 0 Then
  39.             WScript.Echo "已处理 " & linesProcessed & " 行..."
  40.         End If
  41.     Loop
  42.    
  43.     ' 关闭文件
  44.     inputFile.Close
  45.     outputFile.Close
  46.    
  47.     ' 显示完成消息
  48.     MsgBox "文件处理完成!" & vbCrLf & _
  49.            "输入文件: " & inputPath & vbCrLf & _
  50.            "输出文件: " & outputPath & vbCrLf & _
  51.            "处理行数: " & linesProcessed
  52. End Sub
  53. ProcessLargeFile()
复制代码

问题5:脚本在64位系统上的兼容性问题

解决方案:
  1. ' 处理64位系统上的兼容性问题
  2. Function Is64BitOS()
  3.     On Error Resume Next
  4.    
  5.     Dim shell
  6.     Set shell = CreateObject("WScript.Shell")
  7.    
  8.     ' 检查PROCESSOR_ARCHITECTURE环境变量
  9.     Dim procArch
  10.     procArch = shell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
  11.    
  12.     If InStr(1, procArch, "64", vbTextCompare) > 0 Then
  13.         Is64BitOS = True
  14.     Else
  15.         ' 检查PROCESSOR_ARCHITEW6432环境变量
  16.         Dim procArchW64
  17.         procArchW64 = shell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITEW6432%")
  18.         
  19.         If InStr(1, procArchW64, "64", vbTextCompare) > 0 Then
  20.             Is64BitOS = True
  21.         Else
  22.             Is64BitOS = False
  23.         End If
  24.     End If
  25.    
  26.     On Error GoTo 0
  27. End Function
  28. Sub Run32BitScriptOn64BitOS()
  29.     If Is64BitOS() Then
  30.         ' 检查当前是否在32位脚本宿主中运行
  31.         Dim shell
  32.         Set shell = CreateObject("WScript.Shell")
  33.         
  34.         Dim sysWow64
  35.         sysWow64 = shell.ExpandEnvironmentStrings("%SystemRoot%") & "\SysWOW64"
  36.         
  37.         If Not fso.FolderExists(sysWow64) Then
  38.             ' 32位子系统不存在,无法运行32位脚本
  39.             MsgBox "无法在64位系统上运行32位脚本"
  40.             Exit Sub
  41.         End If
  42.         
  43.         ' 重新在32位脚本宿主中运行脚本
  44.         Dim scriptPath
  45.         scriptPath = WScript.ScriptFullName
  46.         
  47.         Dim command
  48.         command = "%SystemRoot%\SysWOW64\wscript.exe """ & scriptPath & """"
  49.         
  50.         shell.Run command, 0, False
  51.         
  52.         ' 退出当前脚本
  53.         WScript.Quit
  54.     Else
  55.         ' 在32位系统上直接运行
  56.         MsgBox "正在32位系统上运行脚本"
  57.     End If
  58. End Sub
  59. ' 在脚本开始处调用
  60. Run32BitScriptOn64BitOS()
复制代码

结论

VBScript是一种强大而灵活的脚本语言,特别适合在Windows环境中实现自动化任务。通过本文的学习,您已经掌握了VBScript的基础知识、高级技巧以及实际应用案例。从简单的变量操作到复杂的系统管理,VBScript都能胜任。

要真正掌握VBScript,关键在于实践。尝试将日常工作中重复性的任务自动化,您将发现VBScript的强大之处。随着经验的积累,您将能够编写更复杂、更高效的脚本,进一步提高工作效率。

记住,学习编程是一个持续的过程。不断探索、实践和学习,您将成为一名出色的VBScript开发者,能够利用这一强大工具解决各种实际问题。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则

关闭

站长推荐上一条 /1 下一条

手机版|联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.

>