VB 实例

五个可直接用的脚本:批量改名、日志统计、生成报告、清理临时文件、弹窗提醒。

Intermediate
Key PointsVBScript 最实用的场景是「在 Windows 上快速做一件小事」,不需要装任何环境。

1. 批量改名

VBSCRIPT
Option Explicit

Dim fso, folder, f, baseName, i
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("C:\photos")
baseName = "IMG_"
i = 1

For Each f In folder.Files
    If LCase(fso.GetExtensionName(f.Name)) = "jpg" Then
        f.Name = baseName & Right("000" & i, 3) & ".jpg"
        i = i + 1
    End If
Next

WScript.Echo "已重命名 " & (i - 1) & " 个文件"
Output
已重命名 128 个文件

Assigning f.Name renames the file. Right("000" & i, 3) zero-pads: i = 7 gives 007. Renaming changes iteration order, so do not rely on the original sequence.

Bulk renames are irreversible. Dry-run on a copy first: replace the assignment with WScript.Echo f.Name & " -> " & newName, check the output, then run for real.

2. 日志统计

VBSCRIPT
Option Explicit

Dim fso, ts, line, total, errors, warns, pct
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("C:\logs\app.log", 1)      ' 1 = 只读

total = 0 : errors = 0 : warns = 0

Do While Not ts.AtEndOfStream
    line = ts.ReadLine
    total = total + 1
    If InStr(line, "[ERROR]") > 0 Then errors = errors + 1
    If InStr(line, "[WARN]") > 0 Then warns = warns + 1
Loop
ts.Close

If total > 0 Then
    pct = Round(errors * 100 / total, 2)
Else
    pct = 0
End If

WScript.Echo "总行数:" & total
WScript.Echo "错误:" & errors & "(" & pct & "%)"
WScript.Echo "警告:" & warns
Output
总行数:18420
错误:37(0.2%)
警告:215

InStr returns a position or 0 when absent, so compare > 0 rather than to True. Guard total = 0 separately or the division raises an error.

3. 生成报告

VBSCRIPT
Option Explicit

Dim fso, ts, i, row, total
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.CreateTextFile("C:\reports\summary.csv", True)

ts.WriteLine "日期,订单数,金额"
total = 0
For i = 1 To 5
    row = DateAdd("d", -i, Date())
    ts.WriteLine FormatDateTime(row, 2) & "," & (10 + i) & "," & (1000 * i)
    total = total + 1000 * i
Next
ts.WriteLine "合计,," & total
ts.Close

WScript.Echo "报告已生成,合计 " & total
Output
报告已生成,合计 15000

FormatDateTime(row, 2) yields yyyy-mm-dd, avoiding 2026/11/3 which Excel may misparse. For Chinese content, make sure the file encoding matches what Excel expects.

4. 清理临时文件

VBSCRIPT
Option Explicit

Dim fso, folder, f, cutoff, deleted, freed
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("C:\temp")
cutoff = DateAdd("d", -7, Now())          ' 7 天前
deleted = 0 : freed = 0

For Each f In folder.Files
    If f.DateLastModified < cutoff Then
        freed = freed + f.Size
        f.Delete True
        deleted = deleted + 1
    End If
Next

WScript.Echo "删除 " & deleted & " 个文件,释放 " & _
             Round(freed / 1048576, 1) & " MB"
Output
删除 43 个文件,释放 128.6 MB

Deleting while enumerating usually works in VBScript (the Files collection re-enumerates), but collecting names first and deleting afterwards is safer.

Cleanup scripts need guards: a specific directory, specific extensions, and a minimum age. A wrong one can wipe a disk in seconds — test on a throwaway directory first.

5. 弹窗提醒

VBSCRIPT
Option Explicit

Dim answer
answer = MsgBox("会议 10 分钟后开始,现在去吗?", _
                vbYesNo + vbQuestion + vbSystemModal, "提醒")

If answer = vbYes Then
    CreateObject("WScript.Shell").Run "https://meeting.example.com/room/42"
End If
Output
(弹出对话框)
会议 10 分钟后开始,现在去吗?
[是]  [否]

MsgBox returns button constants: vbYes(6), vbNo(7), vbOK(1), vbCancel(2). vbSystemModal keeps the dialog above all windows, which suits reminders.

VBSCRIPT
' 配合任务计划:每天 9:00 提醒
' 任务计划程序 → 创建基本任务 → 启动程序
'   程序:wscript.exe
'   参数:C:\scripts\remind.vbs

脚本的通用骨架

VBSCRIPT
Option Explicit

' 1. 参数校验
Dim args
Set args = WScript.Arguments
If args.Count < 1 Then
    WScript.Echo "用法:cscript " & WScript.ScriptName & " <目录>"
    WScript.Quit 1
End If

' 2. 主逻辑放在 Sub 里
Sub Main()
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FolderExists(args(0)) Then
        WScript.Echo "目录不存在:" & args(0)
        WScript.Quit 2
    End If
    ' ... 实际工作 ...
End Sub

' 3. 统一错误处理
On Error Resume Next
Main
If Err.Number <> 0 Then
    WScript.Echo "失败:" & Err.Description
    WScript.Quit 3
End If

Four parts: argument checks, main logic, error handling, exit code. The script then works both manually and from Task Scheduler or batch files, and callers can detect failure.

WScript.Arguments reads command-line arguments under cscript and shortcut properties under wscript. Arguments containing spaces must be quoted or they split.

Friends & Partners