VB 用法

怎么运行 VBScript:cscript、wscript、ASP、以及调试手段。

Beginner
Key Points命令行用 cscript 看输出,双击用 wscript 弹框,网页里用 ASP 或(仅 IE)客户端脚本。

命令行运行

Bash
cscript //nologo hello.vbs
OptionMeaning
//nologo不打印版本信息
//B屏蔽弹窗与输入
//T:30最多运行 30 秒
//Job:xxx运行 .wsf 里指定的作业

双击运行

Double-clicking uses wscript: WScript.Echo becomes a dialog and WScript.StdOut is unavailable. To see console output when double-clicking, detect the host in the script or use a .wsf file that specifies cscript.

XML
<!-- run.wsf:强制用 cscript 运行 -->
<job id="main">
  <script language="VBScript" src="hello.vbs"/>
</job>

在 ASP 里用

ASP
<%
    Dim total, i
    total = 0
    For i = 1 To 10
        total = total + i
    Next
    Response.Write "1 到 10 的和是 " & total
%>
Output
1 到 10 的和是 55

There is no WScript object in ASP: output uses Response.Write and input uses Request. Same language core, different host, different available objects.

调试手段

VBSCRIPT
' 1. 打印中间值
WScript.Echo "i = " & i & ", total = " & total

' 2. 断言式检查
If total < 0 Then
    WScript.Echo "异常:total 不应为负"
    WScript.Quit 1
End If

' 3. 出错时停止并报告
On Error Resume Next
DoSomething
If Err.Number <> 0 Then
    WScript.Echo "错误 " & Err.Number & ":" & Err.Description
    WScript.Quit 1
End If

WScript.Quit 1 returns a non-zero exit code so callers (batch files, Task Scheduler) can detect failure. Echoing without quitting makes a broken script look successful.

常见运行问题

SymptomCause
No output用 wscript 跑了,StdOut 不可用
Object requiredSet 漏了,或对象为 Nothing
Permission denied写系统目录、注册表需要管理员
Script blocked组策略或杀软禁止 WSH
Chinese garbled文件编码与代码页不一致
.vbs files must be saved as ANSI (GBK) or UTF-16 LE; UTF-8 garbles Chinese strings. This is the biggest friction between VBScript and modern tooling, which defaults to UTF-8.

安全性

WSH can read and write files, edit the registry and launch processes, so it is a favourite of malicious scripts. Enterprises often disable it by policy or allow only signed scripts — if your script will not run on a corporate machine, ask IT about that policy.

Friends & Partners