VB 总结

语法要点回顾、常见陷阱、与 PowerShell 的取舍。

Beginner
Key PointsVBScript 的语法很小,难的是记住它的几个「和别的语言不一样」的地方。

语法速览

VBSCRIPT
Option Explicit                       ' 强制声明

Dim x, arr(3)                         ' 变量与数组
Const MAX = 100                       ' 常量
x = 10
arr(0) = "a"

If x > 5 Then                         ' 条件
    WScript.Echo "大"
ElseIf x = 5 Then
    WScript.Echo "等"
Else
    WScript.Echo "小"
End If

Select Case x                         ' 多分支
    Case 1 : WScript.Echo "一"
    Case Else : WScript.Echo "其它"
End Select

For i = 1 To 3                        ' 计数循环
Next

For Each v In arr                     ' 遍历
Next

Do While x > 0                        ' 条件循环
    x = x - 1
Loop

Sub DoIt(a)                           ' 过程
End Sub

Function Calc(a)                      ' 函数
    Calc = a * 2
End Function

和别的语言不一样的地方

PointVBScriptMost languages
Case sensitivity不区分区分
Statement end换行分号
Block endEnd If / Next / Loop}
Param passing默认 ByRef默认按值或引用
Return给函数名赋值return
Boolean ops不短路短路
Break / continue只有 Exitbreak / continue
String concat&+

陷阱清单

  • 变量拼错不报错 —— 不加 Option Explicit 就新建变量
  • **And / Or 不短路** —— If obj Is Nothing Or obj.X 会崩
  • **"0" 是真** —— 字符串非空即真
  • **Dim a(2) 是 3 个** —— 括号里是最大下标
  • **默认 ByRef** —— 函数里改了会影响外面
  • 文件编码 —— 必须 ANSI 或 UTF-16,UTF-8 会乱码

和 PowerShell 的取舍

FeatureVBScriptPowerShell
Availability所有 Windows 都有Win7+ 默认有
Objects只有 COM完整 .NET
Pipeline没有有,强
Error handlingOn Error Resume Nexttry/catch
DebuggingEcho 打印断点、ISE、VS Code
Future弃用中微软主推

Write new scripts in PowerShell. Reading VBScript is still essential for maintenance: many enterprises still run .vbs logon scripts, scheduled tasks and deployment scripts.

迁移到 PowerShell

VBSCRIPT
' VBScript:列出目录下的 .log 文件
Dim fso, folder, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("C:\logs")
For Each f In folder.Files
    If LCase(Right(f.Name, 4)) = ".log" Then
        WScript.Echo f.Name & " " & f.Size
    End If
Next
POWERSHELL
# PowerShell:同样的事
Get-ChildItem C:\logs -Filter *.log |
    ForEach-Object { "{0} {1}" -f $_.Name, $_.Length }

The PowerShell version is shorter and emits objects, so Sort-Object, Where-Object and Export-Csv work directly. VBScript emits strings and you parse them yourself.

Migration is not line-by-line translation: a For Each plus If in VBScript is often one Where-Object, and a Select Case is often a hashtable. Decide the outcome first, then write PowerShell — far cleaner than transliterating.

继续学习

  1. PowerShell —— Windows 自动化的现在与未来
  2. COM 与 WMI —— 理解 VBScript 为什么能操作系统
  3. Python —— 跨平台的自动化脚本
  4. 批处理 —— 更老但仍在用的胶水

Friends & Partners