windows 脚本宿主 wsh - baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf ·...

26
第一部分 Windows Script Host 进行脚本编程 1 Windows 脚本宿主 WSH 本章主要内容开始学习如何编写和运行脚本文件本章针对脚本编程脚本语言和用来运行脚本的命令给出一个概览在开始编写脚本之后可以返回本章来复习关于脚本调试器Script Debugger的内容1.10 节介绍了在互联网上的何处可以查找答案并获取更多信息1.1 什么是 Windows 脚本 简单来说这个问题的答案是Windows 脚本是用一种解释型语言编写的程序它通过 COM 对象模 型访问 OS 组件尽管这一答案很精确但对于除了计算机科学家以外的人来说这个答案用处不大认为脚本很重要每个人都需要了解因此让我们再次尝试来描述它1.1.1 Script部分 要说明脚本是什么以及为什么需要知道如何编写它先花些时间来思考一下脚本script这个词最 初的字面含义喜剧脚本是一个规划是用来表演一幕剧作的一系列指令所有必需的单词都带有一些指 这些指令告诉演员向哪里走动以及在此过程中做些什么脚本展示出该规划并且依赖于有能力的演 员来完成实际的工作脚本指导演员执行现实生活中熟悉的动作一次又一次地重复重复的次数与剧作 演出的次数相同而你只是坐在那里观看从软件的角度出发你可能会猜测到脚本是一类计算机程序但是单词脚本强调了我在前面 提到的几点它们或多或少以直白的英语编写它们利用有能力的演员来执行困难的工作脚本只是告诉演员做什么它们为你执行现实生活中的任务而你只是坐在那里观看

Upload: others

Post on 25-May-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第一部分

用 Windows Script Host 进行脚本编程

第 1 章

Windows 脚本宿主(WSH)

本章主要内容:

• 开始学习如何编写和运行脚本文件。

• 本章针对脚本编程、脚本语言和用来运行脚本的命令给出一个概览。

• 在开始编写脚本之后,可以返回本章来复习关于脚本调试器(Script Debugger)的内容。

• 1.10 节介绍了在互联网上的何处可以查找答案并获取更多信息。

1.1 什么是 Windows 脚本

简单来说,这个问题的答案是“Windows 脚本是用一种解释型语言编写的程序,它通过 COM 对象模

型访问 OS 组件”。尽管这一答案很精确,但对于除了计算机科学家以外的人来说,这个答案用处不大。我

认为脚本很重要,每个人都需要了解,因此,让我们再次尝试来描述它。

1.1.1 “Script”部分

要说明脚本是什么,以及为什么需要知道如何编写它,先花些时间来思考一下脚本(script)这个词最

初的字面含义。喜剧脚本是一个规划,是用来表演一幕剧作的一系列指令。所有必需的单词都带有一些指

令,这些指令告诉演员向哪里走动以及在此过程中做些什么。脚本展示出该规划,并且依赖于有能力的演

员来完成实际的工作。脚本指导演员执行现实生活中熟悉的动作,一次又一次地重复,重复的次数与剧作

演出的次数相同,而你只是坐在那里观看。

从软件的角度出发,你可能会猜测到,脚本是一类计算机程序,但是,单词“脚本”强调了我在前面

提到的几点:

• 它们或多或少以直白的英语编写。

• 它们利用有能力的“演员”来执行困难的工作,脚本只是告诉“演员”做什么。

• 它们为你执行现实生活中的任务,而你只是坐在那里观看。

Page 2: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 2  第一部分 用 Windows Script Host 进行脚本编程 

脚本不是一个新的概念。从 AutoCAD 到 z/OS,程序和操作系统已经包含脚本功能长达数十年之久。

Windows 脚本宿主(Windows Script Host,WSH)首次出现在 Windows 95 Service Release 2 版中,尽管现

在已经几乎没人知道这一点。并且,你将会在随后的各章中看到,你可以让各种各样的“演员”(软件组件

和程序)来处理数据、管理计算机,或者更高效地完成你的工作。

1.1.2 “Windows”部分

WSH 用于编写脚本来操作文件、处理数据、更改操作系统设置、安装和卸载软件、发送电子邮件等

等 , 这些操作是通过访问其他程序(很多这样的程序随 Windows 提供,你还可以随后添加更多程序)来做

到的,而实际工作是其他程序做的。打个比方,脚本就如同剧院中的“演员”。这是非常强大的概念,因为

脚本编程软件自身只需要告诉其他的程序,它想要做什么,而不必知道执行该工作的细节。这意味着,脚

本所能够做的事情范围,不会受到脚本语言的限制,即 Windows 脚本编程是可扩展的。

用 Microsoft 的术语来说,这些外部的软件组件包装成对象。对象是自包含的程序模块,它们通过一

组定义良好的编程连接来为其他程序执行任务。对象通常用来表示现实世界中的一些物体或概念,例如文

件、电子表格或计算机用户账户以及编程连接,编程连接为其他程序(例如,脚本)提供一种方式,以获

得有关对象所表示的信息并操作对象的内容。对象是我们习惯使用的一个概念,我们将在第 3 章介绍它。

现在,我只是提到 WSH 所带的对象组件,而这些对象可用于访问文件和文件夹、Email 系统、网络系统、

Windows 服务和设备驱动、Active Directory,以及 Windows 其他的很多内容。

这里举个例子:假设我工作中有这样一件经常要做的事,人们要发送 Word 文档(休假申请)给我,这些文

档必须分发给公司内的几个人,该文档在每天的不同时刻通过 Email 的形式出现,并且,我将附件文档保存到一

个文件夹中。每天下午 5 点钟,我必须向公司的管理层发送一封电子邮件,提交该日的所有申请并附上附件。

我可以每天手工完成这项工作,但是,我也可以编写一个脚本来完成它。只需轻轻点击一下,脚本就

可以利用内建的 Windows 对象来执行如下的任务:

• 获取“to be sent”文件夹中的所有文件列表。

• 编写一条 Email 消息并且用公司管理层的地址列表作为地址。

• 将每个文件附加到 Email 中然后发送它。

• 将申请过的文件放入“taken care of ”文件夹中。

只需轻轻点击鼠标就完成这项工作,每天都能 17 点钟下班,而不是 17 点 10 分才下班,这岂不是更好?

你不会仅限于使用 Windows 所提供的对象组件。很多软件公司都销售插件组件,它们为脚本和

Windows 程序提供各种服务,从网络到图形显示到数据库访问。

此外,脚本可以利用众多的应用程序,例如 Microsoft Word 和 Excel。用术语来讲,它们暴露了表示这

些文档、电子表格等的对象。如果你编写过 Word 或 Excel 宏,你已经在利用这些功能了。Windows 脚本也

可以操作这些对象。例如,脚本可以执行如下的任务:

• 使用 Word 列出计算机上的所有文件。

• 创建一个 Excel 图表,来显示每个网络用户占用了多少硬盘空间。

• 创建并维护一个数据库,列出所有的计算机及其网络设置。

这些只是几个例子。最后,如果你能够用 C、C++、Visual Basic 或任何其他的编程语言来编写程序,

你可以创建自己的插件对象。

1.1.3  “Host”部分

WSH 的“宿主”(Host)指的是,Microsoft 将其脚本系统划分为两个部分 :一个部分(脚本宿主)负

责管理脚本的组件对象,另一部分(脚本语言引擎)真正解释脚本语言自身。这种分工使得你可以使用任

Page 3: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 3 

意几种编程语言来编写脚本。你可以根据个人偏好选择好几种语言。换句话说,WSH 充当语言引擎(用于

解释你选择编写脚本的语言)和执行实际工作的组件或对象之间的中介,如图 1-1 所示。

例如,如下的示例脚本使用 VBScript 语言编写,它获取计算机用户的登录名并显示:

12 Chapter 1 Windows Script Host

Figure 1.1 WSH acts as the intermediary between a scripting language engine and objects.

For example, the following sample script written in the VBScript language obtains thecomputer user’s logon name and displays it:

set wnet = CreateObject(“WScript.Network”)uname = wnet.UserNameMsgBox “Your user name is “ & uname

In this example,VBScript and WSH don’t actually do the job of finding the logonname. Instead, they use the WScript.Network object, which can provide informationabout and make changes to the Windows Networking environment.This is illustratedgraphically in Figure 1.2.

Scripting LanuageEngine (Interpreter)

Windows ScriptHostYour Script

Object Object Object…

VBScript LanguageInterpreter

WScript.NetworkObject

Windows Script Hostshowname.vbs

Figure 1.2 A script can use the WScript.Network object to obtain the current user’s logon name.

The point of this is that WSH provides a simple, efficient way for you to take advan-tage of hundreds of software modules provided with Windows and other add-onapplications.

Just as you can add to the collection of component objects provided with Windows,you can add interpreters for other programming languages beyond to the two thatMicrosoft provides. I discuss this later in the chapter.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 12

在这个示例中,VBScript 和 WSH 不会真正去做查找登录名的工作,而是使用 WScript.Network 对象,

该对象可以提供相关的信息并对 Windows 网络环境做出修改,如图 1-2 所示。

12 Chapter 1 Windows Script Host

Figure 1.1 WSH acts as the intermediary between a scripting language engine and objects.

For example, the following sample script written in the VBScript language obtains thecomputer user’s logon name and displays it:

set wnet = CreateObject(“WScript.Network”)uname = wnet.UserNameMsgBox “Your user name is “ & uname

In this example,VBScript and WSH don’t actually do the job of finding the logonname. Instead, they use the WScript.Network object, which can provide informationabout and make changes to the Windows Networking environment.This is illustratedgraphically in Figure 1.2.

Scripting LanuageEngine (Interpreter)

Windows ScriptHostYour Script

Object Object Object…

VBScript LanguageInterpreter

WScript.NetworkObject

Windows Script Hostshowname.vbs

Figure 1.2 A script can use the WScript.Network object to obtain the current user’s logon name.

The point of this is that WSH provides a simple, efficient way for you to take advan-tage of hundreds of software modules provided with Windows and other add-onapplications.

Just as you can add to the collection of component objects provided with Windows,you can add interpreters for other programming languages beyond to the two thatMicrosoft provides. I discuss this later in the chapter.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 12

脚本语言引擎

(解释器)

脚本Windows脚本宿主

对象 对象 对象

图 1-1  WSH 充当脚本语言引擎和对象之间的中介 图 1-2  脚本可以使用 WScript.Network 对象来获取 当前用户的登录名

这说明,WSH 提供了一种简单、高效的方式,来利用 Windows 和其他的插件应用程序所提供的数以百

计的软件模块,这很关键。

就像可以往 Windows 所提供的组件对象集合添加内容一样,除了 Microsoft 提供的两种语言(及其解

释器),你也可以为其他编程语言添加解释器。我将在本章稍后介绍这一点。

1.1.4 与编写批处理文件有何不同

如果你使用 PC 有些年头了,经历过 Windows 诞生之前的那些日子,你可能熟悉批处理文件。批处理文

件也是脚本,可用来将要运行的一系列程序编写成脚本,查看和处理文件,并且可以充当一种基本的编程语

言。批处理文件如今仍然有用。我将在本书第 11 章中详细介绍它们。然而在这里,我想要介绍脚本编程。

批处理文件的主要局限是,它们只能启动程序,不能为你提供与程序交互的方式。批处理文件在整个

程序和文件的层级工作。这对于某些任务来说可能很好。然而,通常批处理文件不允许使用对象以及操作

文本和数字,也不能提供像 VBScript 或 JScript 这样的编程语言的强大功能。简而言之,脚本编程是实现

Windows 自动化的一种更现代化和更强大的方式。

1.2 脚本语言

脚本本身是可以使用 Notepad 这样的简单文本编辑器来编辑的文本文件。文本文件中包含的是使用

脚本语言编写的指令。你可以根据自己的偏好从几种语言中选择一种,下面我将介绍这些可选的语言。

Windows 7、Windows Vista、Windows XP 和 Windows 2000 带有两款脚本语言解释器 :VBScript 和JScript。使用二者之一,可以做相当多的事情。也有其他的强大的脚本编程语言可以使用,并且,你可以

自由地将它们添加到 WSH。在本节中,我介绍了目前可用的最常见的脚本编程语言。

脚本编程语言 VS. 编译型语言

使用任何脚本与使用 C++ 这样的标准编译型编程语言一样,所编程序可做同样的工作。那么,

VBScript 这样的解释型语言与编译型语言之间的区别是什么?

Showname:vbs

Page 4: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 4  第一部分 用 Windows Script Host 进行脚本编程 

解释型语言以纯文本的形式存储在计算机上,并且,每次运行它们的时候,都要一行一行地查看,

以确定要告诉计算机做些什么。编译型程序只分析一次,并且转换为处理器可以直接理解的硬件“机器

指令”。结果,编译型的程序运行得更快。然而,解释型的语言不需要转换的步骤,因此,当你在编写

或优化它们的时候,这会节省一些时间。解释型的语言也更容易学习和理解,并且,可以根据你的需求

变化来修改它们。

对于我们在本书中所讨论的相对较小的处理性工作,使用一种编译型语言所带来的复杂性超过了其

速度快的优点。

1.2.1 VBScriptVBScript 中的 VB 表示 Visual Basic,Visual Basic 是从 1964 在 Dartmouth 大学诞生的 Basic 演进而

来,并且有了很大的发展和变化。45 年过去了,Basic 仍然是一种很好的“入门”编程语言,并且,在

Microsoft 的手中,它变成了一种有用的现代语言。

VBScript 是 Microsoft 开发的 Visual Basic 的几个版本之一。VBScript 是在 WSH 中使用的一种方言,

并且,它也可以用于 Web 浏览器和服务器中。Visual Basic for Applications(VBA)是针对 Microsoft 桌面产品(如 Word 和 Excel)开发的脚本语言或宏语言。完整的 Visual Basic 用于开发产品来构建独立的

Windows 程序,其最新的版本是 VB.NET,它可以用来开发使用 Microsoft 的 .NET Framework 技术的桌面

和 Web 应用程序。

VBScript 可能是最容易学习的脚本编程语言,并且,由于在 Microsoft Word、Excel 以及其他几款广泛

使用的应用程序中,也使用它来编写宏(脚本),它可能是学习软件开发最佳的第一门编程语言。编写宏或

脚本的经验,都可以很容易地用于学习其他内容。

1.2.2 JScriptJScript 是模仿 Netscape 的 JavaScript 语言的一种编程语言(Microsoft 使自己的版本具备了其前竞争对

手的功能,但也使其略有不同,以保证其受人关注和不兼容)。该语言作为将编程能力构建到 Web 页面中

的一种方式来设计。你看到过这样的 Web 页面吗 ? 当鼠标移动的时候,页面的菜单或图片会改变,这很可

能是使用 JScript 或 JavaScript 来做到的,因为这是大多数 Web 浏览器所支持的脚本语言。

注意 JavaScript 和 JScript 不是 Java。JavaScript 是一种完全独立的语言,它表面上与 Java 有一些相似

性,但是,众所周知,实际上它们不是一回事。正如前面所提到的,JScript 是 JavaScript 的一种,因此,

它也不是 Java。JScript 可以用于 Windows 脚本编程,并且,由于一些人有着编写 Web 页面脚本和服务器端脚本的经

验,他们也选择使用 JScript 语言。

正如我所提到的,VBScript 和 JScript 的解释器都是作为 WSH 包的一部分提供的,而 WSH 安装在

Windows 2000 以后的所有 Windows 版本之上。可以从第三方或者从 Microsoft 的 Windows Resource Kits 获取其他的语言 , 我将在以下小节列出其中某些语言。

1.2.3 PerlPerl 于 1987 年由 Unix 社区中的开发者所开发。从一开始,Perl 就是一种“开放的”语言,它的编写、

调试以及后续的开发,都是由公众自由进行的。它是一种流行的、功能强大的语言,特别适合用于操作文

本。它有着广泛的字符串处理和模式匹配功能,以及主流编程语言的所有其他功能。

Perl 也是晦涩难懂的。即便对于有经验的程序员来说,Perl 程序也难以阅读和理解(我们开玩笑地称其

为 Write-Only 的语言)。然而,Linux 社区还是拥抱和推进 Perl,并且互联网上有大量的 Perl 脚本可用。对

Page 5: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 5 

于你想做的任何事情,往往都已经有了相应的 Perl 脚本。

ActiveState 公司将自己标榜为“为跨平台开发提供开源的产品和服务的领先提供商”,它已经将 Perl 打包为“WSH 可用的”语言,并且,可以从 www.activatestate.com 免费下载它。ActiveState 的产品是功能完

备的、集成到 Windows 的 Perl 版本,同时,它也是 Perl 爱好者的必备版本。

1.2.4 PythonPython 是源自阿姆斯特丹的国家数学和计算机研究院的一款流行脚本 / 编程语言。它是一款可移植的

面向对象的语言,不像 Perl 那么晦涩,并且在 Linux 社区很受欢迎。

可以从 www.activestate.com 下载一个免费的 Python 的 WSH 插件。

1.2.5 Open Object REXXREXX 起源于 1979 年,是 IBM 大型机的脚本语言。从那时起,IBM 已经开发了用于 IBM Linux、

AIX、OS/2 和 Windows 以及其大型机操作系统的版本。Open Object REXX 是其最新的 Windows 版本。它

最初是一款正式的 IBM 产品,但 IBM 已经在开源的计划中发布了它。请访问 www.oorexx.org 以了解详细

信息。

1.2.6 RubyRuby 是起源于日本的一种较新语言。它目前在欧洲和日本比在美国更流行,但是,它正渐有起色。从

http://arton.hp.infoseek.co.jp 可以获取 Ruby 到 WSH 的一个插件,你也可以在 Web 上搜索“ActiveScriptRuby”。

注意 如果你所喜欢的脚本语言并没有在这里列出来,查看一下该脚本语言是否有一个支持 WSH 的版

本。如果你找到了,请告诉我。只需要访问 www.helpwin7.com/scripting 并留言就行了。

1.2.7 选择一种语言

在本书中,我重点介绍 VBScript,因为它是脚本语言中最常用且最“普通”的一种。

如果你使用多种 Microsoft 产品,VBScript 绝对是应学习的最重要的语言,因为它还在 Word、Excel、Access 和很多其他的 Microsoft 产品中用做内建的宏语言。Unix 和 Linux 爱好者当然会为 Perl和 Python 唱赞歌,但是,如果你打算只学习一种语言,并且使用 Microsoft 的应用程序,我推荐你学习

VBScript。为此,下一章将介绍 VBScript 并提供一个简短的教程。遗憾的是,教授任何其他语言,所需的篇幅都

过多。如果你熟知或喜欢任何其他的、可用的脚本语言,我鼓励你使用它们。在第 3 章中,我展示了如何

用几种替代的语言来访问 Windows 对象。然后,你就能够将我在本书后面给出的示例都翻译为你所选择的

语言了。

注意 在第 4 章到第 9 章中的示例里,我只使用 VBScript。我曾经考虑教授 VBScript 和 JScript,并且以多种语言提供示例脚本。然而,我最终决定不这

么做。与用多种语言重复每个示例的做法相比,只提供 VBScript 的话,我就能够给出更多种示例

脚本来。我还认为,VBScript 更适合作为第一门脚本编程语言来学习,因为它可以用于很多其他的

Microsoft 应用程序中。

对于已经了解其他脚本语言的读者来说,我意识到这会让你的工作更困难一点。如果你已经对一

门喜爱的语言有了足够的经验,我认为本书中的 VBScript 示例的多样性和深度足以让你进行语言转换

的工作。

1.3 一个简单的脚本

好了,理论和概览都介绍得足够多了,可向你展示一个实际示例,来说明我所讨论的内容了。如下是

Page 6: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 6  第一部分 用 Windows Script Host 进行脚本编程 

一段脚本,它会查看一个给定的目录(文件夹)中的所有文件,并且显示所有文件总的字节大小:

16 Chapter 1 Windows Script Host

NoteIf you have a preferred scripting language that’s not listed here, check to see whether a WSH-enabled

version is available. If you find one, please let me know. Just visit www.helpwin7.com/scripting and leave

me a message.

Choosing a LanguageIn this book, I focus on VBScript because it’s the most common and the most“vanilla” of the scripting languages.

If you use many Microsoft products,VBScript is definitely the most important language to learn because it’s used inside Word, Excel,Access and many otherMicrosoft products as the built-in macro language. Unix and Linux enthusiasts rightlysing the praises of Perl and Python, but if you’re going to learn just one language, andyou work with Microsoft applications, I recommend learning VBScript.

To that end, the next chapter covers VBScript and provides a brief tutorial.Unfortunately, it would take many more pages than we can spare for this book toteach any of the other languages. If you know and love any of the other availablescripting languages, I encourage you to use them. In Chapter 3, I show you how toaccess Windows objects in several alternative languages.You should then be able totranslate the examples I give in the remainder of the book to your language of choice.

NoteI use VBScript exclusively in the sample scripts in Chapters 4–9.

I considered teaching both VBScript and JScript and providing sample scripts in multiple languages.

However, I decided against this. With the VBScript-only approach, I can provide a greater variety of sam-

ple scripts than I could if I had to repeat each one in several languages. I also think that VBScript is the

better choice as a first scripting language due to its applicability in many other Microsoft applications.

For readers who already know another scripting language, I realize I’m making your job a little more

difficult. If you already have enough experience to have a preferred language, however, I think the greater

variety and depth of the VBScript examples in this book will make the translation work worthwhile.

A Simple ScriptSo, enough with the philosophy and overview! It’s time to show you a practical exam-ple of what I’ve been talking about. Here is a script that examines all the files in agiven directory (folder) and displays the total size of all the files in bytes:

1 ‘ script0101.vbs2 ‘ total up space used in a given directory

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 16

17A Simple Script

3 dir = “C:\”45 set Fsys = CreateObject(“Scripting.FileSystemObject”)6 totsize = 07 for each file in Fsys.GetFolder(dir).Files8 totsize = totsize + file.size9 next10 wscript.echo “The total size of the files in” , dir, “is” , totsize, “bytes”

In this example, the script is set up to tally all the files in the root directory of the harddrive (C:\).What I’ve shown here is the contents of a file I named script0101.vbs.

I should point out that the preceding printed listing contains a number in front ofeach of the 10 lines of text, so I can refer to them in the discussion that follows.Thesenumbers aren’t in the script file itself. If you type the script in yourself, omit thesenumbers.

NoteYou don’t need to type it yourself. I’ve made all the named and numbered sample scripts shown in this

book available for download from www.helpwin7.com/scripting. Follow the link tto download the sample

script ZIP file. The download page has instructions and tips on installing and running the sample scripts.

Now, if I double-click this file in Windows Explorer on my computer, the dialog boxshown in Figure 1.3 appears. (If you’ve downloaded the sample script files, you can tryit on your computer.)

Figure 1.3 Result displayed when the sample script file is double-clicked.

NoteDouble-clicking the file on your computer might not work. For security reasons, some people or compa-

nies configure their Windows computers not to run VBS scripts with just a double-click. If this happens

to you, don’t worry; just read on.

To see how this dialog box appeared, let’s take a look at the contents of the script file,line-by-line. If you’re not familiar with VB or programming in general, don’t worry(yet).We cover the programming details in Chapter 2,“VBScript Tutorial.”

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 17

在这个示例中,脚本会计算硬盘根目录(C:\)下的所有文件的总的大小。我在这里给出的,是我命名

为 script0101.vbs 的一个文件。注意,在前面 10 行文本中,每一行前面有一个编号,这是为了方便在后面

的讨论中引用它们。这些行号不是脚本文件自身的内容。如果你自己输入脚本的话,请省略这些行号。

注意 你不需要自己输入代码,我已经在 www.helpwin7.com/scripting 提供了本书中所有命名的和编号的示例脚本

的下载。请按照这个链接下载示例脚本的 ZIP 文件。下载

页面给出了关于安装和运行示例脚本的说明和提示。

现在,如果 在 我 的 计 算 机 的 Windows 资 源 管 理 器

(Windows Explorer)中双击这个文件,对话框如图 1-3 所示

(如果你下载了示例脚本文件,可以在自己的计算机上尝试

一下)。

注意 在你的计算机上,双击该文件可能无效。出于安全的原因,一些个人或公司将他们的 Windows计算机配置为不能只是双击就运行 VBS 脚本。如果你遇到这种情况,不要担心,请继续阅读。

要看看这个对话框是如何出现的,让我们来一行一行地看看该脚本文件的内容。如果你还不熟悉 VB或缺乏一般的编程知识,不要担心。我们将在第 2 章中介绍编程细节。

第 1 行和第 2 行是注释。在 VBScript 中,单引号(')之后的任何内容都会被忽略。注释对 Windows没有任何意义。其作用是帮助人们理解这段脚本是干什么的。最好为你的所有脚本添加注释,以说明它们

做什么以及如何做到。在较长的脚本中,可以详细地说明情况。在这段脚本中,简短地说明脚本做什么就

足够了。注意,这段脚本以一个注释开头,注释给出了脚本文件的名称。我这么做,可方便你从下载的所

有示例脚本中找到它。

第 3 行指定了需要计算其内容的文件夹的名称。

第 4 行是空行。使用空行把一段程序或脚本的各个部分从视觉上分隔开,这是一种很好的编程风格。

尽管 WSH 不要求这么做,但是,当用空白(也就是空行)分隔开程序中的某些步骤的时候,你和其他的人

都会更容易阅读和理解程序。

第 5 行使用名为 Scripting.FileSystemObject 的一个编程组件(即对象),该对象允许脚本深入探究

硬盘和文件夹,并且获取关于其中的文件的信息。VBScript 没有将这一功能内建到语言自身之中,但是

FileSystemObject 对象这么做了,并且,我们可以在自己的程序中使用该对象。

第 6 行设置了计数器(即一个变量,用于累加),我们使用它来计算所有文件的总的大小。它从 0 开

始,并且将每个文件的大小添加给它。

第 7 行到第 9 行构成了一个循环,针对选定的目录中的每个文件,将循环中的每行执行一次。注意,

我缩进了循环中的文本。VBScript 不要求必须使用缩进,这只是让读者容易看到循环的开头和结尾,并且,

17A Simple Script

3 dir = “C:\”45 set Fsys = CreateObject(“Scripting.FileSystemObject”)6 totsize = 07 for each file in Fsys.GetFolder(dir).Files8 totsize = totsize + file.size9 next

10 wscript.echo “The total size of the files in” , dir, “is” , totsize, “bytes”

In this example, the script is set up to tally all the files in the root directory of the harddrive (C:\).What I’ve shown here is the contents of a file I named script0101.vbs.

I should point out that the preceding printed listing contains a number in front ofeach of the 10 lines of text, so I can refer to them in the discussion that follows.Thesenumbers aren’t in the script file itself. If you type the script in yourself, omit thesenumbers.

NoteYou don’t need to type it yourself. I’ve made all the named and numbered sample scripts shown in this

book available for download from www.helpwin7.com/scripting. Follow the link tto download the sample

script ZIP file. The download page has instructions and tips on installing and running the sample scripts.

Now, if I double-click this file in Windows Explorer on my computer, the dialog boxshown in Figure 1.3 appears. (If you’ve downloaded the sample script files, you can tryit on your computer.)

Figure 1.3 Result displayed when the sample script file is double-clicked.

NoteDouble-clicking the file on your computer might not work. For security reasons, some people or compa-

nies configure their Windows computers not to run VBS scripts with just a double-click. If this happens

to you, don’t worry; just read on.

To see how this dialog box appeared, let’s take a look at the contents of the script file,line-by-line. If you’re not familiar with VB or programming in general, don’t worry(yet).We cover the programming details in Chapter 2,“VBScript Tutorial.”

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 17

图 1-3 当双击示例文件的时候显示的结果

Page 7: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 7 

这有助于我们理解程序。

第 8 行做实际的工作 :它将 Windows 目录中的每个文件的大小累加到名为 totsize 的变量中。当循环对

每个文件做完此操作,我们得到了目录中所有文件的总的大小。

在 VBScript 中,等号(=)用在这里并不像其在数学中的含义那样,表示“两个事物是相等的”。该程

序行告诉 VBScript,获取变量 totsize 中的值,给其加上值 file.size,这就是所涉及的文件的大小,然后将结

果放入到变量 totsize 中(如果计算机键盘有更多的符号可用,VBScript 可能设计为可以这样编写 :totsize <= totsize + file.size)。

第 10 行以普通英文显示了结果。默认情况下,echo 命令在一个弹出对话框中显示文本。

这是一段相当简单的脚本,不是很有用,但是,它确实说明了关于 Windows 脚本的几个重要之处:

• 脚本语言拥有批处理语言所欠缺的高级编程功能,例如,变量和循环(并不完全是这样,批处理文件

也有原始的变量和循环,但是,这里要强调的是,它们真的很原始)。

• 脚本可以利用对象来扩展语言的额外功能。

• 脚本可以与操作系统交互(例如,通过查看一个文件夹中的文件的相关信息),并且可以与人交互

(例如,以格式化的文本来显示结果)。

• 脚本可以通过使用空白来让程序的结构易于识别,从而让程序更易于理解。

• 脚本文件可以有并且应该有注释,来描述和记录脚本做什么工作以及如何工作。注释能清楚地记录特

定的工作是如何完成的,这使得脚本文件成为一种重要的文档形式。

1.4 脚本文件的类型

脚本文件是普通的、基本的文本文件,你可以使用 Notepad 来编辑它。在文件中是编程语句,按照所

使用的脚本语言可以理解的语法写出来。

要让 Windows 知道你的脚本使用何种语言,在命名脚本文件的时候,必须使用一种一致的文件命名方

案。最重要的部分是扩展名或文件类型,例如,myscript.vbs 的扩展名是 .vbs。如果你编写 VBScript 的话,

你必须使用这一扩展名。默认情况下,Windows 资源管理器在列出文件名的时候不会显示扩展名,它只显

示 myscript,并作为一个 VBScript 脚本文件列出。

提示 我认为让 Windows 资源管理器隐藏扩展名是一个糟糕的想法。要让扩展名可见,打开任何

Windows 资源管理器窗口(例如,My Computer(我的电脑)或 My Documents(我的文档))。在

Windows 7 和 Vista 中,按下并释放 Alt 键,以弹出菜单。点击 Tools(工具)、Folder Options(文件夹

选项)。选择 View(查看)标签页。在 Advanced Settings(高级设置)列表中,找到 Hide Extensions For Known File Types(隐藏已知文件类型的扩展名)并不选中该选项。然后,点击确定按钮。

在使用脚本的过程中,你可能会遇到各种各样的扩展名。表 1-1 给出了常见的一些。

表 1-1 脚本文件扩展名

扩 展 名 文 件 类 型

.js JScript 脚本

.jse JScript 已编码脚本

.pls Perl 脚本

.vbe VBScript 已编码脚本

Page 8: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 8  第一部分 用 Windows Script Host 进行脚本编程 

扩 展 名 文 件 类 型

.vbs VBScript 脚本

.wsc Windows 脚本组件

.wsf Windows 脚本文件(XML 格式)

.wsh WSH 设置

注意 如果你使用 WSH 的一个较早的版本,并且创建带有 .wsh 扩展名的文件,在 WSH 5 及其以后的

版本中,你需要将其重新名为 .wsf。如果你使用 Perl 脚本,并且安装了 RealAudio’s Real Player 的话,要小心。它试图从 Perl 脚本那里

劫持 .pls 文件扩展名。如果发生这种情况,首先在 Real Player 中关闭 Audio Playlist 媒体类型。然后,在

Windows 7 和 Vista 中,打开 Control Panel(控制面板),点击 Programs(程序)、Make a File Type Always Open in a Specific Program(始终使用指定的程序打开此文件类型),并且在该窗口中选择对 .pls 文件的

关联。如果它不是 Microsoft Console Based Script Host,点击 Change Program(更改)并找到 \windows\system32\cscript.exe。在 Windows XP 上,打开 Windows 资源管理器,点击 Tools(工具)、Folder Options(文件夹选项)和 File Types(文件类型)。在列表中找到 PLSFile,并且在那里选择关联。

其他的脚本语言也使用特定的扩展名,每种语言的文档说明了它们通常使用什么扩展名。

你可能对表 1-1 中列出的一些文件名并不熟悉,因此,我将在后续的小节中更详细地介绍它们。如果

你刚开始编写脚本的话,这里只需要暂时略过它们就行了,你并不会立即用到所有这些知识。

1.4.1 JSE 和 VBE :已编码脚本

一些脚本由商业软件开发者编写,并且需要一定使用许可费。这些开发者很注意防止自己的工作成

果被任意复制和泄露。还有一些由系统管理员编写的脚本,管理员也不希望偷窥者和修改者了解公司运

作的细节。为了帮助这些开发者,一些脚本语言提供了编码工具来压缩或加密脚本文件,以便使它们不

容易阅读。

Microsoft 提供了一款可下载的编码工具,来编码 VBScript 和 JScript 文件。它可将 VBScript .vb 文件转

换为编码的 .vbe 文件,并且将 .js 文件转换为编码的 .jse 文件。可以从 www.microsoft.com 下载该工具,搜

索“Script Encoder”并点击 Download Details 结果。

小心 Script Encoder 使得别人难以阅读已编码脚本,但并非不可能阅读它。高级黑客仍然可以解码文

件。因此不要在脚本中放置密码或其他的敏感信息,即便使用了编码工具进行加密。

1.4.2 Windows 脚本文件(WSF)为了帮助维护和编写成组的复杂脚本,Microsoft 开发了一种文件格式,可将数个单独的脚本存储到一

个文本文件中,甚至可在一段脚本中使用几种语言。新的文件格式叫做 Windows 脚本文件(Windows Script File,WSF),并且使用 .wsf 扩展名。

举例比说明更容易理解,因此,让我们先给出示例:

21Types of Script Files

files.You can download the utility from www.microsoft.com. Search for “ScriptEncoder” and click the Download Details result.

CautionThe Script Encoder makes it difficult, but not impossible, for others to read the contents of a script. The

determined hacker could still decode the file. Do not put passwords or other confidential information in a

script, even if it’s encoded.

Windows Script Files (WSF)To help maintain and write complex sets of scripts, Microsoft developed a file formatthat allows several separate scripts to be stored in one text file and even lets you useseveral languages in one script.The new file format is called a Windows Script File(WSF), and the extension used is .wsf.

It’s easier to show than explain, so I show it first:

<package><job id=”script1”>

<script language=”VBScript”>WScript.Echo “This is script 1!”

</script></job>

<job id=”script2”><script language=”JScript”>

WScript.Echo(“This is script 2!”);</script>

</job>

<job id=”script3”><script language=”VBScript” src=”c:\scriptlib\anotherfile.vbs” />

</job></package>

WSFs are still plain-text files, but they’re structured with text markup called tags.Thismight look familiar to you if you’ve ever done web design because this looks a lot likeHypertext Markup Language (HTML), which is used to create web pages. However,this markup is called Extensible Markup Language (XML), and its required structure isvery strict. XML is used to indicate where the beginning and end of the pieces of ascript go. XML isn’t a script programming language itself.

In this example, you can see that three separate script fragments exist in this file,delimited by <package>, <job>, and <script> tags.

Each separate script, which would otherwise have to be in a separate .vbs or .js file,is placed between <job> and </job> tags.The ID attribute gives a name to each.This

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 21

(续)  

Page 9: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 9 

21Types of Script Files

files.You can download the utility from www.microsoft.com. Search for “ScriptEncoder” and click the Download Details result.

CautionThe Script Encoder makes it difficult, but not impossible, for others to read the contents of a script. The

determined hacker could still decode the file. Do not put passwords or other confidential information in a

script, even if it’s encoded.

Windows Script Files (WSF)To help maintain and write complex sets of scripts, Microsoft developed a file formatthat allows several separate scripts to be stored in one text file and even lets you useseveral languages in one script.The new file format is called a Windows Script File(WSF), and the extension used is .wsf.

It’s easier to show than explain, so I show it first:

<package><job id=”script1”>

<script language=”VBScript”>WScript.Echo “This is script 1!”

</script></job>

<job id=”script2”><script language=”JScript”>

WScript.Echo(“This is script 2!”);</script>

</job>

<job id=”script3”><script language=”VBScript” src=”c:\scriptlib\anotherfile.vbs” />

</job></package>

WSFs are still plain-text files, but they’re structured with text markup called tags.Thismight look familiar to you if you’ve ever done web design because this looks a lot likeHypertext Markup Language (HTML), which is used to create web pages. However,this markup is called Extensible Markup Language (XML), and its required structure isvery strict. XML is used to indicate where the beginning and end of the pieces of ascript go. XML isn’t a script programming language itself.

In this example, you can see that three separate script fragments exist in this file,delimited by <package>, <job>, and <script> tags.

Each separate script, which would otherwise have to be in a separate .vbs or .js file,is placed between <job> and </job> tags.The ID attribute gives a name to each.This

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 21

WSF 仍然是普通的文本文件,但是,它们使用叫做标签的文本标记来构造。如果你从事过 Web 设计的

话,可能会眼熟,因为它看上去很像是超文本标记语言(Hypertext Markup Language,HTML),这是用来

创建 Web 页面的语言。然而,这一标记叫做可扩展的标记语言(Extensible Markup Language,XML),并

且,它要求结构非常严格。XML 用来说明一段脚本从何处开始以及到何处结束。XML 本身不是一种脚本

编程语言。

在这个示例中,你可以看到文件中存在 3 层隔开的脚本段,分别用 <package>、<job> 和 <script> 标签隔开。

每段单独的脚本,要放在 <job> 和 </job> 标签之间,否则这些脚本必须放在一个单独的 .vbs 或 .js 文件

中。ID 属性给每个脚本段一个名称。这可能有点令人混淆,但是,这么做的目的是允许你将多个脚本段放

入到一个文件中,以便只需要复制和更新一个文件。当你运行该脚本文件的时候,可以通过 job 名称来选择

想要的脚本,我将在本章稍后介绍这一点。

WSF 文件有趣的一点是,你可以将不同的语言脚本部分组合到同一个文件中,甚至是组合到同一个

job 中,只需要用 <script> 和 </script> 标签将一段程序包围起来就可以了。这些标签指明了该段程序是用何

种语言编写的。注意,在示例中,第一个 job 是用 VBScript 编写的,而第二个是用 JScript 编写的。如果你

安装了其他语言的话,也可以使用它们。

第三个 job 展示了 WSF 文件的另一特殊的功能:能够提取其他文件中的脚本的一部分。在这个示例中,

名为 script3 的程序提取自文件 c:\scriptlib\anotherfile.vbs。注意,<script> 标签是以 /> 结束的,而不是通常

的 >。这是一个特殊的标识,是 XML 语言所必需的,表明没有对应的 </script> 结束标签。<script> 标签有

两种形式。它可以包含一些程序文本,如下所示:

22 Chapter 1 Windows Script Host

can seem confusing, but the purpose is to let you put many scripts in one file, so youhave only one file to copy and keep up-to-date.You can choose the desired script byits job name when you run the script file—I describe this later in the chapter under“Wscript and Cscript Command Options.”

What makes WSF files interesting is that you can combine different language scriptcomponents in the same file, and even in the same job, by surrounding the bits of pro-gram with <script> and </script> tags.These tags specify in which language the bitof program is written. Notice in the example that the first job is written in VBScript,whereas the second is written in JScript.You can use other languages as well, if youhave them installed.

The third job demonstrates another special feature of WSF files: the capability to pullin parts of the script from other files. In the example, script3’s program is pulled infrom the file c:\scriptlib\anotherfile.vbs. Notice that this <script> tag ends with/> instead of the usual >.This is a special indicator, required by the XML language,and indicates that there is no matching </script> end tag.The <script> tag comes intwo forms. It can surround some program text, as shown here:

<script language=”VBscript”>VBScript programming goes hereThere might be lots of it

</script>

It can also indicate that the script program is to be pulled in from somewhere else:

<script language=”Vbscript” src=”path or URL” />

In the second form of the <script> tag, the src entry tells WSH where to find thematerial to read in.This can be in the form of a full file and path or even a URL, inwhich case the material is obtained from an Internet location.This feature makes itpossible to store commonly used bits of script programming once, where it can beused by many scripts. In Chapter 2, where we discuss VBScript programming withsubroutines and functions, I have more to say on this topic.

Finally, the <package> tag surrounds the entire file. If more than one separate job existsin the file, the file must start with <package> and end with </package>, as shown inthe example. If there’s just one job, <package> and </package> can be omitted.

NoteThere’s quite a bit more to the WSF file format. I discuss it in more detail in Appendix G, “Creating Your

Own Scriptable Objects,” that you can download from www.helpwin7.com/scripting.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 22

它也可以表示脚本程序从其他某个地方提取:

22 Chapter 1 Windows Script Host

can seem confusing, but the purpose is to let you put many scripts in one file, so youhave only one file to copy and keep up-to-date.You can choose the desired script byits job name when you run the script file—I describe this later in the chapter under“Wscript and Cscript Command Options.”

What makes WSF files interesting is that you can combine different language scriptcomponents in the same file, and even in the same job, by surrounding the bits of pro-gram with <script> and </script> tags.These tags specify in which language the bitof program is written. Notice in the example that the first job is written in VBScript,whereas the second is written in JScript.You can use other languages as well, if youhave them installed.

The third job demonstrates another special feature of WSF files: the capability to pullin parts of the script from other files. In the example, script3’s program is pulled infrom the file c:\scriptlib\anotherfile.vbs. Notice that this <script> tag ends with/> instead of the usual >.This is a special indicator, required by the XML language,and indicates that there is no matching </script> end tag.The <script> tag comes intwo forms. It can surround some program text, as shown here:

<script language=”VBscript”>VBScript programming goes hereThere might be lots of it

</script>

It can also indicate that the script program is to be pulled in from somewhere else:

<script language=”Vbscript” src=”path or URL” />

In the second form of the <script> tag, the src entry tells WSH where to find thematerial to read in.This can be in the form of a full file and path or even a URL, inwhich case the material is obtained from an Internet location.This feature makes itpossible to store commonly used bits of script programming once, where it can beused by many scripts. In Chapter 2, where we discuss VBScript programming withsubroutines and functions, I have more to say on this topic.

Finally, the <package> tag surrounds the entire file. If more than one separate job existsin the file, the file must start with <package> and end with </package>, as shown inthe example. If there’s just one job, <package> and </package> can be omitted.

NoteThere’s quite a bit more to the WSF file format. I discuss it in more detail in Appendix G, “Creating Your

Own Scriptable Objects,” that you can download from www.helpwin7.com/scripting.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 22

在 <script> 标签的第二种形式中,src 项告诉 WSH 从哪里找到要读取的内容。这可能是一个完整的文

件和路径形式,甚至可以是一个 URL,URL 会指明从一个 Internet 位置来获取内容。这一功能使得我们能

够将常用的脚本程序片段只保存一次,却可以放在那里供很多脚本使用。在第 2 章中,我们介绍 VBScript编程的子例程和函数的时候,将会更多地讨论这一话题。

最后,<package> 标签包含了整个文件。如果文件中存在多个单独的 job,文件必须以 <package> 开头

而以 </package> 结束,如本示例所示。如果只有一个 job,<package> 和 </package> 可以省略。

注意 还有其他几种 WSF 文件格式。我将在附录 G 中更详细地介绍,可以从 www.helpwin7.com/scripting 下载附录 G。

Page 10: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 10  第一部分 用 Windows Script Host 进行脚本编程 

1.4.3 Windows 脚本组件

Windows 脚本组件文件(Windows Script Components,WSC)是添加了 XML 结构标记的另一种类型的脚

本文件。WSC 允许你开发自己的编程“对象”,以供脚本和其他的程序使用。我在附录 G 中介绍了组件。

1.4.4 WSH 设置

如果用鼠标右键点击一个脚本文件的图标,然后选择 Properties(属性),Windows 在 Properties 页面上

显示一个专门的 Script(脚本)标签页,这是脚本所独有的标签页,如图 1-4 所示。

这里,你可以指定在系统认定脚本“死亡”之前允许它

运行多久,并且,可以禁止 Microsoft 的版权提示,当脚本以

命令行模式运行的时候通常会显示这样的提示。如果你在这个

Properties 页面更改了默认的设置,Windows 会将信息存储到与脚

本文件具有相同主文件名的一个文件中,但是,扩展名为 .wsh。WSH 文件没有其他的内容和功能,只是保存这些设置。

也可以在运行脚本的时候通过命令行来设置这些选项,但

是,介绍这些内容有点超前了。我们先回头来看看基础的内容,

并看看如何从头创建一个新的脚本文件。

1.5 创建第一个脚本文件

正如我在本章前面所提到的,你可以使用任何能够处理纯

文本文件的文本编辑器来创建脚本文件。Windows 所附带的

Notepad,就能完成这项工作,因此,让我们用它在计算机上输

入一个脚本文件。在本节中,我将带领你一步一步地进行(稍

后,我建议你使用一款更好的脚本编辑程序,但是,对于这个例

子,Notepad 很好用)。

1.5.1 创建一个脚本文件夹并使其安全化

让我们先来创建一个文件夹,专门用来保存脚本。如果你将自己的脚本放在同一个地方,可以更容易

地找到并修改它们,并且,正如我们在本章稍后所讲到的,在一个 Command Prompt(命令提示符)窗口中

使用它们会更容易。按照如下的步骤进行:

1. 点击 Start(开始)、[All] Programs(所有程序)、Accessories(附件)和 Command Prompt(命令提示符)。

(在本书后续部分中,我将其描述为“打开一个命令提示符窗口”)。

2. 输入如下 3 条命令,在每条命令之后按下回车键:

24 Chapter 1 Windows Script Host

Creating Your First Script FileAs I mentioned earlier in this chapter, you can create script files with any text editingprogram that can deal with plain-text files.The Notepad accessory that comes withWindows can do this, so let’s use it to type in a script file on your computer. I walkyou through the steps in this section. (Later, I suggest that you get a better script edit-ing program, but for this example, Notepad is fine).

Making and Securing a Script FolderTo start, let’s make a folder just to hold scripts. If you keep your scripts in one place,you can find and modify them more easily, and as we see later in this chapter, usethem in a Command Prompt window more easily. Follow these steps:

1. Click Start, [All] Programs,Accessories, Command Prompt.

(For the remainder of this book, I write “Open a Command Prompt window.”)

2. Type the following three commands, pressing Enter after each one:

c:mkdir \scriptscd \scripts

Now, anyone else who uses your computer can see and use the scripts in this folder.However, you definitely do not want other users to be able to modify your scripts;otherwise, they can make your script do something undesired, such as to make theiraccount a Computer Administrator.The next time you ran your script, it would dotheir bidding using your account’s privileges.You might never even know this hap-pened, so you have to make sure that only you can modify your scripts.

NoteThis is the unfortunate nitty-gritty part that you just have to do to make Windows secure against not

just hackers, but accidents and casual interference. Take solace in knowing that you have to do this just

one time.

To secure your scripts folder on Windows 7,Vista and XP Professional, follow thesesteps. If you have Windows XP Home Edition, you can perform these steps only ifyou boot your computer in Safe Mode. (You might not feel that it’s worth the troublein this case). Do the following:

1. Click Start, [My] Computer.

2. Under Computer, under Folders, click Local Disk (C:).

3. In the right pane, locate your scripts folder. Right-click it and selectProperties.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 24

现在,使用你的计算机的任何人都可以看到并使用这个文件夹中的脚本。然而,你肯定不想让其他用

户修改你的脚本,否则,他们可能用你的脚本做一些你不希望的事情,例如,让他们自己的账户成为计算

机管理员。下一次你运行自己的脚本的时候,可能是使用你的账户的权限来听从他们的命令。你甚至可能

根本不知道发生了这种情况,因此,你必须确保只有自己能够修改脚本。

注意 这是真正遗憾的事情,你必须做些事情来保证 Windows 安全,不仅要防范黑客,还要防止意外

和随意的干扰。好在你只需要这么做一次。

23Types of Script Files

Windows Script Components (WSC)A Windows Script (WSC) Component file is another type of script file with XMLstructure markup added to it. Component files let you develop your own programming“objects” to be used by scripts and other programs. I discuss components in Appendix G.

WSH SettingsIf you right-click the icon for a script file and then select Properties,Windows displaysa special Script tab on the Properties page that’s unique to that script, as shown inFigure 1.4.

Figure 1.4 The Properties page for a script file contains a Script tab.

Here, you can specify how long the script is allowed to run before the system consid-ers it “dead,” and you can inhibit the Microsoft copyright notice that’s usually printedwhen scripts are run in command-line mode. If you change the default settings onthis Properties page,Windows stores the information in a file with the same rootname as the script file, but with the extension .wsh.WSH files have no other contentor function than to hold these settings.

These options can also be set on the command line when you run the script, but I’mgetting ahead of myself. Let’s get back to basics and see how to create a new script filefrom scratch.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 23

图 1-4  脚本文件的 Properties 页面包

含一个 Script 标签页

Page 11: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 11 

在 Windows 7、Vista 和 XP Professional 上,要保障自己的脚本文件夹的安全,只需要按照如下步骤进

行。如果你使用的是 Windows XP Home Edition,只有当你以安全模式重新启动计算机之后,才能够执行这

些步骤(你会觉得如此大费周章是值得的)。执行如下操作:

1. 选择 Start(开始),[My] Computer([ 我的 ] 电脑)。

2. 在 Computer(计算机)下,Folders(文件夹)下,点击 Local Disk (C:)(本地磁盘 (C:))。3. 在右侧面板中,找到你的脚本文件夹。鼠标右键点击它并选择 Properties(属性)。

4. 选择 Security(安全)。

5. 在 Group Or User Names(组或用户名)下,依次点击 Authenticated Users、Users 和 Everyone(对于

所出现的任何这些名称)。在选中了每一个之后,看看底部是否选中了 Write(写入)或 Modify(修改)。不

应该选中它们。如果没有选中这些账户,跳转到步骤 9。然而,如果对于这些名称中的任何一个选中了 Modify(修改)或 Write(写入),点击 Advanced(高级)

按钮并且进行步骤 6。6. 在 Windows 7 上,点击 Change Permissions(更改权限)。在 Vista 上,点击 Edit(编辑)。不要选中

Include Inheritable Permissions From This Object’s Parent(包含可从该对象的父项继承的权限),并且,在最

终的对话框中,点击 Copy(添加)。

7. 对每个名称 Users、Authenticated Users 和 Everyone 重复如下的步骤(如果有这些名称的话):

a. 在 Name(名称)栏中,选择 Users 并点击 Edit(编辑)。

b. 确保(靠近顶部的)Apply To(应用于)项设置为 This Folder,Subfolders and Files(此文件夹、子

文件夹和文件)。如果必要的话修改它。

c. 确保只有如下的 4 个复选框是选中的 :Traverse Folder/Execute File(遍历文件夹 / 执行文件)、

List Folder/Read Data(列出文件夹 / 读取数据)、Read Attributes(读取属性)和 Read Extended Attributes(读取扩展属性)。去掉选择其他复选框,然后点击 OK(确定)。

对于后续的其他名称(如果列出了它们的话),重复这 3 个步骤 :先是 Authenticated Users,然后是 Everyone。

8. 点击 OK(确定)。

9. 你应该位于最初的 Scripts Properties(脚本)对话框中。在 Vista 和 Windows 7 中,点击 Edit(编辑)

按钮。

10. 点击 Add(添加),然后是 Advanced(高级),接着点击 Find Now(立即查找)。在 Search Results(搜

索结果)下找到你自己的账户,双击它,然后点击 OK(确定)。

11. 你的账户现在应该出现在 Group Or User Names(组或用户名称)列表中。在底部,选中 Full Control(完全控制)(如果 Windows 允许的话);否则,Modify(修改)就足够了。

12. 点击 OK(确定),然后,就完成了。

现在,你有了一个持久的、安全的文件夹,可用来保存脚本。

将来,你可以通过如下的步骤返回到这个文件夹:

  1)打开一个命令提示符窗口。

  2)输入如下两条命令:

  

25Creating Your First Script File

4. Select the Security tab.

5. Under Group Or User Names, click Authenticated Users, Users and Everyone,in turn, for any of these names that appear.After selecting each one, look at thebottom part and see whether Write or Modify is checked.They shouldn’t be. Ifthey aren’t checked for any of these accounts, skip to step 9.

However, if either Modify or Write is checked for even one of these names,click the Advanced button and proceed to step 6.

6. On Windows 7, click Change Permissions. On Vista, click Edit. UncheckInclude Inheritable Permissions From This Object’s Parent, and in the resultingdialog box, click Copy.

7. Repeat the following three steps for each of the names Users,AuthenticatedUsers, and Everyone, if they appear:

a. In the Name column, select Users, and click Edit.

b. Make sure that the Apply To item (near the top) is set to This Folder,Subfolders and Files. Change it if necessary.

c. Make sure that only four boxes are checked:Traverse Folder/Execute File,List Folder/Read Data, Read Attributes, and Read Extended Attributes.Uncheck any other box, and then click OK.

Repeat these three steps for the following other names, if they are listed:Authenticated Users, and then Everyone.

8. Click OK.

9. You should be at the original Scripts Properties dialog box. On Vista andWindows 7 click the Edit button.

10. Click Add, then Advanced, and then click Find Now. Locate your own accountunder Search Results, double-click it, and then click OK.

11. Your account should now appear in the list of Group Or User Names. In thebottom part, check Full Control, if Windows lets you; otherwise, Modify is goodenough.

12. Click OK, and you’re finished.

Now, you have a permanent, secured folder set up to hold scripts.

In the future, you can return to this folder by following these steps:

1. Open a Command Prompt window.

2. Type the following two commands:

c:cd \scripts

Later, I show you how to put this folder into your computer’s PATH list, so you canrun the script by typing its name in any Command Prompt window. Now, though,let’s create a first script.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 25

稍后,我将介绍如何将这个文件夹放入到你的计算机的 PATH 列表中,以便你可以在任何命令提示符

窗口中通过输入脚本的名称来运行它们。现在,让我们来创建第一个脚本。

Page 12: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 12  第一部分 用 Windows Script Host 进行脚本编程 

1.5.2 创建脚本

在通过命令提示符窗口打开脚本文件夹之后,输入如下的命令:

26 Chapter 1 Windows Script Host

Creating a ScriptAfter you have a Command Prompt window opened up to your script folder, type thefollowing command:

notepad firstscript.vbs

This opens Notepad.Type the following command, exactly as printed here:

wscript.echo “This is output from my first script”

Click File, Save, and then close Notepad. Now, type the following command into theCommand Prompt window:

wscript firstscript.vbs

This should pop up a small window with the text This is output from my firstscript.What you did is to tell Windows to run the wscriptWSH processing programon the script file firstscript.vbs, and the script told Windows to display the message.

Click OK to close the message window.You’ve now created and run your own script.

To create new scripts in the future, you can use these same steps:

n Open a Command Prompt window.n If you want to put the script into your general-purpose script folder, type the c:

and cd \scripts commands. (You can create scripts in other drives and folders,if you want; just type a different drive letter or folder path.)

n Type notepad followed by the name of the script.

TipWhenever you create a new script file, open a Command Prompt window and type the word notepad

followed by the name of the file you want to create, for example:

notepad newscript.vbs

You can also specify a path, if you want the file to be placed in a specific folder, for example:

notepad c:\scripts\newscript.vbs

When Notepad asks if you’d like to create a new file, click Yes.

If you started Notepad without typing the filename on the command line, when you saved your new

script using File, Save As, the script is saved with the name newscript.vbs.txt and you’d have to

rename it. Putting the filename on the command line avoids this problem.

You can also use your \scripts folder to hold scripts you acquire from others ordownloaded from the Internet.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 26

这会打开 Notepad。严格按照如下格式输入命令:

26 Chapter 1 Windows Script Host

Creating a ScriptAfter you have a Command Prompt window opened up to your script folder, type thefollowing command:

notepad firstscript.vbs

This opens Notepad.Type the following command, exactly as printed here:

wscript.echo “This is output from my first script”

Click File, Save, and then close Notepad. Now, type the following command into theCommand Prompt window:

wscript firstscript.vbs

This should pop up a small window with the text This is output from my firstscript.What you did is to tell Windows to run the wscriptWSH processing programon the script file firstscript.vbs, and the script told Windows to display the message.

Click OK to close the message window.You’ve now created and run your own script.

To create new scripts in the future, you can use these same steps:

n Open a Command Prompt window.n If you want to put the script into your general-purpose script folder, type the c:

and cd \scripts commands. (You can create scripts in other drives and folders,if you want; just type a different drive letter or folder path.)

n Type notepad followed by the name of the script.

TipWhenever you create a new script file, open a Command Prompt window and type the word notepad

followed by the name of the file you want to create, for example:

notepad newscript.vbs

You can also specify a path, if you want the file to be placed in a specific folder, for example:

notepad c:\scripts\newscript.vbs

When Notepad asks if you’d like to create a new file, click Yes.

If you started Notepad without typing the filename on the command line, when you saved your new

script using File, Save As, the script is saved with the name newscript.vbs.txt and you’d have to

rename it. Putting the filename on the command line avoids this problem.

You can also use your \scripts folder to hold scripts you acquire from others ordownloaded from the Internet.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 26

点击 File(文件)、Save(保存),然后关闭 Notepad。现在,在命令提示符窗口中输入如下命令:

26 Chapter 1 Windows Script Host

Creating a ScriptAfter you have a Command Prompt window opened up to your script folder, type thefollowing command:

notepad firstscript.vbs

This opens Notepad.Type the following command, exactly as printed here:

wscript.echo “This is output from my first script”

Click File, Save, and then close Notepad. Now, type the following command into theCommand Prompt window:

wscript firstscript.vbs

This should pop up a small window with the text This is output from my firstscript.What you did is to tell Windows to run the wscriptWSH processing programon the script file firstscript.vbs, and the script told Windows to display the message.

Click OK to close the message window.You’ve now created and run your own script.

To create new scripts in the future, you can use these same steps:

n Open a Command Prompt window.n If you want to put the script into your general-purpose script folder, type the c:

and cd \scripts commands. (You can create scripts in other drives and folders,if you want; just type a different drive letter or folder path.)

n Type notepad followed by the name of the script.

TipWhenever you create a new script file, open a Command Prompt window and type the word notepad

followed by the name of the file you want to create, for example:

notepad newscript.vbs

You can also specify a path, if you want the file to be placed in a specific folder, for example:

notepad c:\scripts\newscript.vbs

When Notepad asks if you’d like to create a new file, click Yes.

If you started Notepad without typing the filename on the command line, when you saved your new

script using File, Save As, the script is saved with the name newscript.vbs.txt and you’d have to

rename it. Putting the filename on the command line avoids this problem.

You can also use your \scripts folder to hold scripts you acquire from others ordownloaded from the Internet.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 26

这时会弹出一个小窗口,其中带有文本 This is output from my first script。你所做的事情,是告诉

Windows,在脚本文件 firstscript.vbs 上运行 wscript WSH 处理程序,并且,该脚本让 Windows 显示消息。

点击 OK 关闭消息窗口。你现在已经创建并运行了自己的脚本。

要在将来创建新的脚本,可以使用如下的步骤:

• 打开一个命令提示符窗口。

• 如果你想要将脚本放入到自己的通用脚本目录下,输入 c: 和 cd \scripts 命令(如果你愿意,也可以在

其他硬盘上和文件夹中创建脚本;只要输入不同的硬盘符号或文件夹路径就行了)。

• 输入 notepad,后面跟着脚本的名称。

提示 无论何时创建一个新的脚本文件,打开一个命令提示符窗口,并且输入 notepad,后面跟着想要

创建的文件的名称,例如:

26 Chapter 1 Windows Script Host

Creating a ScriptAfter you have a Command Prompt window opened up to your script folder, type thefollowing command:

notepad firstscript.vbs

This opens Notepad.Type the following command, exactly as printed here:

wscript.echo “This is output from my first script”

Click File, Save, and then close Notepad. Now, type the following command into theCommand Prompt window:

wscript firstscript.vbs

This should pop up a small window with the text This is output from my firstscript.What you did is to tell Windows to run the wscriptWSH processing programon the script file firstscript.vbs, and the script told Windows to display the message.

Click OK to close the message window.You’ve now created and run your own script.

To create new scripts in the future, you can use these same steps:

n Open a Command Prompt window.n If you want to put the script into your general-purpose script folder, type the c:

and cd \scripts commands. (You can create scripts in other drives and folders,if you want; just type a different drive letter or folder path.)

n Type notepad followed by the name of the script.

TipWhenever you create a new script file, open a Command Prompt window and type the word notepad

followed by the name of the file you want to create, for example:

notepad newscript.vbs

You can also specify a path, if you want the file to be placed in a specific folder, for example:

notepad c:\scripts\newscript.vbs

When Notepad asks if you’d like to create a new file, click Yes.

If you started Notepad without typing the filename on the command line, when you saved your new

script using File, Save As, the script is saved with the name newscript.vbs.txt and you’d have to

rename it. Putting the filename on the command line avoids this problem.

You can also use your \scripts folder to hold scripts you acquire from others ordownloaded from the Internet.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 26

如果想要把文件放在一个特定的目录中,也可以指定一个路径,例如:

26 Chapter 1 Windows Script Host

Creating a ScriptAfter you have a Command Prompt window opened up to your script folder, type thefollowing command:

notepad firstscript.vbs

This opens Notepad.Type the following command, exactly as printed here:

wscript.echo “This is output from my first script”

Click File, Save, and then close Notepad. Now, type the following command into theCommand Prompt window:

wscript firstscript.vbs

This should pop up a small window with the text This is output from my firstscript.What you did is to tell Windows to run the wscriptWSH processing programon the script file firstscript.vbs, and the script told Windows to display the message.

Click OK to close the message window.You’ve now created and run your own script.

To create new scripts in the future, you can use these same steps:

n Open a Command Prompt window.n If you want to put the script into your general-purpose script folder, type the c:

and cd \scripts commands. (You can create scripts in other drives and folders,if you want; just type a different drive letter or folder path.)

n Type notepad followed by the name of the script.

TipWhenever you create a new script file, open a Command Prompt window and type the word notepad

followed by the name of the file you want to create, for example:

notepad newscript.vbs

You can also specify a path, if you want the file to be placed in a specific folder, for example:

notepad c:\scripts\newscript.vbs

When Notepad asks if you’d like to create a new file, click Yes.

If you started Notepad without typing the filename on the command line, when you saved your new

script using File, Save As, the script is saved with the name newscript.vbs.txt and you’d have to

rename it. Putting the filename on the command line avoids this problem.

You can also use your \scripts folder to hold scripts you acquire from others ordownloaded from the Internet.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 26

当 Notepad 询问是否要创建一个新的文件,点击 Yes。如果你启动 Notepad 而没有在命令行上输入文件名,当你使用 File(文件)、Save As(另存为)保

存新脚本的时候,脚本会使用名称 newscript.vbs.txt 来保存,并且,你必须重命名它。将文件名放置在

命令行中,则会避免这一问题。

你也可以使用自己的 \scripts 文件夹来保存从其他地方获取的脚本以及从 Internet 上下载的脚本。

1.5.3 脚本编辑工具

在本书中,我展示了如何使用标准的 Windows Notepad 附件来创建和编辑脚本以及其他的批处理文件。

Notepad 肯定能够做这项工作,并且我自己多年来一直使用 Notepad,但是,当我尝试了其他编辑工具,并且

看到它们是如此难以置信的有用时,我不得不摇头叹息,我自己到底是怎么想的?一款好的脚本编辑器,你

只需要花一天时间就可以掌握,而它可以为你节约时间并省却很多麻烦。这里介绍几款好的编辑程序。不管

你是刚开始使用脚本,或者你是一名资深专业人士,我强烈推荐你使用如表 1-2 所示工具中的一种或多种。

表 1-2 第三方脚本编辑工具

程  序 说  明

 VBSEdit

 VBSEdit 不只是一款文本编辑器,它还可以交互地步进执行(调试)脚本,并且可以在此过

程中查看变量的内容。它还提供了一个 Object Browser,我们将在第 3 章中介绍 Object Browser。还包括语法着色和一个“自动完成”功能,后者可以省去你的很多录入工作。可通过 www.vbsedit.com 免费试用,完全解锁需要 59 美元。尝试一下,我保证你不会再使用 Notepad 了

Page 13: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 13 

程  序 说  明

 AdminScriptEditor

 和 VBSEdit 一样,AdminScriptEditor 也包含了语法着色、自动完成,而且它也是一款

交互式的调试器。除此之外,它还添加了向导,帮助你编写复杂的 Windows Management Instrumentation(Windows 管理规范)和 Active Directory(活动目录)脚本,并且,它提供了插

件对象,允许你创建交互式的表单和程序。它还支持 Windows PowerShell。可以花 100 美元从

www.adminscripteditor.com 购买

 PrimalScript  PrimalScript 是一款漂亮的脚本编辑程序。这肯定对 Notepad 是一种冲击,但是,从 www.sapien.com 购买它的价格是 179 美元,它不是给一般用户用的

 UltraEdit

 UltraEdit 并非专门的脚本编辑工具,但是,它值得一提。如果你需要对文本文件或文本数据

做任何正式的编辑,那么,售价 59.55 美元的 UltraEdit 物有所值。它拥有非常多的功能。尽管

它不能帮助你调试脚本,但它能以你需要的任何方式排序、搜索、转换、切分和分割文本。当

编辑脚本文件的时候,它自动高亮显示并着色程序和脚本的关键字以及语法元素。可通过 www.ultraedit.com 获取

1.6 Windows 如何运行脚本

在前面小节的示例中,我提到可以通过在 Windows 资源管理器中双击脚本的文件,或者通过在命令提

示符窗口中输入一条命令,来运行一段脚本。在本节中,我将详细介绍这一点。

1.6.1 Wscript 和 CscriptWSH 有两种形式:名为 Wscript 是一个窗口化版本,名为 Cscript 是一个命令行版本。两种版本都可以

运行任何脚本。二者之间的区别是,窗口化版本(Wscript)使用一个弹出对话框来显示文本输出消息,而

命令行版本(Cscript)通过命令行程序所常见的、常规的“标准输出”方法来显示文本。

要搞清楚我说的意思,执行如下这些步骤:

1. 打开一个命令提示符窗口。

2. 如果你没有通过我在本章前面给出的步骤来创建 firstscript.vbs,现在就去做。如果你已经做过了,

通过输入如下命令返回到 \scripts 文件夹:

28 Chapter 1 Windows Script Host

How Windows Runs ScriptsIn the examples in the previous sections, I mentioned that you can run a script bydouble-clicking its file in Windows Explorer or by typing a command in a CommandPrompt window. In this section, I discuss this in detail.

Wscript and CscriptWSH comes in two flavors: a windowed version named Wscript and a command-lineversion named Cscript. Either version can run any script.The difference between thetwo is that the windowed version (wscript) displays text output messages with a pop-up dialog box, whereas the command-line version (Cscript) displays text through thenormal “standard output” mechanism common to command-line programs.

To see what I mean, follow these steps:

1. Open a Command Prompt window.

2. If you didn’t create firstscript.vbs by following the steps I gave earlier in thechapter under “Creating Your First Script,” do so now. If you did, return to the\scripts folder by typing

c:cd \scripts

3. Type the command wscript firstscript.vbs and press Enter. Click OK toclose the window.

4. Type the command cscript firstscript.vbs and press Enter.This time, themessage appears in the Command Prompt window.

You should see the results shown in Figure 1.5.

Figure 1.5 Output of a sample script run by wscript (top) and cscript (bottom).

Wscript is best suited for scripts that do their work quietly and display very littleinformation to the user—scripts that, for example, just display error messages andmaybe an “I’m finished” message, like our scripting example did earlier in this chapter.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 28

3. 输入命令 wscript firstscript.vbs 并按下 Enter,点击 OK 以关闭窗口。

4. 输入 cscript firstscript.vbs 并按下 Enter。这一次,消息出现在命令提示符窗口中。

应该会看到图 1-5 所示的结果。

28 Chapter 1 Windows Script Host

How Windows Runs ScriptsIn the examples in the previous sections, I mentioned that you can run a script bydouble-clicking its file in Windows Explorer or by typing a command in a CommandPrompt window. In this section, I discuss this in detail.

Wscript and CscriptWSH comes in two flavors: a windowed version named Wscript and a command-lineversion named Cscript. Either version can run any script.The difference between thetwo is that the windowed version (wscript) displays text output messages with a pop-up dialog box, whereas the command-line version (Cscript) displays text through thenormal “standard output” mechanism common to command-line programs.

To see what I mean, follow these steps:

1. Open a Command Prompt window.

2. If you didn’t create firstscript.vbs by following the steps I gave earlier in thechapter under “Creating Your First Script,” do so now. If you did, return to the\scripts folder by typing

c:cd \scripts

3. Type the command wscript firstscript.vbs and press Enter. Click OK toclose the window.

4. Type the command cscript firstscript.vbs and press Enter.This time, themessage appears in the Command Prompt window.

You should see the results shown in Figure 1.5.

Figure 1.5 Output of a sample script run by wscript (top) and cscript (bottom).

Wscript is best suited for scripts that do their work quietly and display very littleinformation to the user—scripts that, for example, just display error messages andmaybe an “I’m finished” message, like our scripting example did earlier in this chapter.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 28

图 1-5 通过 Wscript(上面)和 Cscript(底部)运行的一段示例脚本的输出

Wscript 最适合于安静地执行自己的任务并且向用户显示信息非常少的脚本,例如,只是显示错误消息

(续)  

Page 14: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 14  第一部分 用 Windows Script Host 进行脚本编程 

或可能是一条“I’m finished”消息的脚本,就像在本章前面我们的脚本示例所示的那样。

使用一条弹出消息的好处是,当消息显示的时候,脚本处理会停止,并且一直等到你阅读该消息并关

闭对话框。

Cscript 是 WSH 的命令行版本(或者叫字符或控制台模式版本)。Cscript 在一个命令提示符窗口中显示

结果,这模拟旧式的 DOS 命令行环境。它很适合于产生较多输出的脚本,例如,目录列表,并且适合于你

想要将其输出保存到一个文件中的脚本。

对显示较多的输出的脚本(或者你想要用其他程序处理其输出的脚本),使用 Cscript 的优点是,你可

以使用标准命令行技术将输出重定向到一个文件。如下的命令运行示例文件 script0101.vbs,并且将输出保

存到一个名为 results.txt 的文件中:

29How Windows Runs Scripts

The advantage of using a pop-up message is that the script processing stops while the message is displayed, and it waits until you’ve read the message and closed the dialog box.

Cscript is the command-line (or character or console mode) version of WSH.Cscript displays results in a command prompt window, which mimics the old DOScommand-line environment. It’s best suited for scripts that produce lots of output,such as directory listings, and for scripts whose output you’d like to capture into a file.

The advantage of using Cscript for scripts that display lots of output—or whose out-put you want to process with other programs—is that you can redirect the output to afile using the standard command-line technique.The following command runs thesample script file script0101.vbs and saves the output in a file named results.txt:

cscript script0101.vbs >results.txt

You can view the results by typing:

notepad results.txt

NoteThis is a good way to view the output of a script that generates a lot of text because it would otherwise

scroll by in the command prompt window in a blur.

You can use either script processor according to your preferences. In the next section,I show you the various ways to run scripts.

Ways to Run a ScriptAs you know,Windows usually offers several ways to accomplish the same thingthrough clicking, double-clicking, right-clicking, or dragging things around.This iscertainly true for running scripts.There are six ways to start the processing of a scriptfile, as listed in Table 1.3.

Table 1.3 Ways of Running a Script File

Action Runs Under

Double-click the file in Explorer, a Find Files window, Default hostor the Desktop. (On Windows Vista, a securitywarning might pop up; click Open to run the script.We talk more about this later.)

Right-click the file and select Open. WscriptRight-click the file and select Open with CscriptCommand Prompt.

continues

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 29

你可以通过输入如下命令来查看结果:

29How Windows Runs Scripts

The advantage of using a pop-up message is that the script processing stops while the message is displayed, and it waits until you’ve read the message and closed the dialog box.

Cscript is the command-line (or character or console mode) version of WSH.Cscript displays results in a command prompt window, which mimics the old DOScommand-line environment. It’s best suited for scripts that produce lots of output,such as directory listings, and for scripts whose output you’d like to capture into a file.

The advantage of using Cscript for scripts that display lots of output—or whose out-put you want to process with other programs—is that you can redirect the output to afile using the standard command-line technique.The following command runs thesample script file script0101.vbs and saves the output in a file named results.txt:

cscript script0101.vbs >results.txt

You can view the results by typing:

notepad results.txt

NoteThis is a good way to view the output of a script that generates a lot of text because it would otherwise

scroll by in the command prompt window in a blur.

You can use either script processor according to your preferences. In the next section,I show you the various ways to run scripts.

Ways to Run a ScriptAs you know,Windows usually offers several ways to accomplish the same thingthrough clicking, double-clicking, right-clicking, or dragging things around.This iscertainly true for running scripts.There are six ways to start the processing of a scriptfile, as listed in Table 1.3.

Table 1.3 Ways of Running a Script File

Action Runs Under

Double-click the file in Explorer, a Find Files window, Default hostor the Desktop. (On Windows Vista, a securitywarning might pop up; click Open to run the script.We talk more about this later.)

Right-click the file and select Open. WscriptRight-click the file and select Open with CscriptCommand Prompt.

continues

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 29

注意 这是查看脚本输出会产生很多文本的一种好办法,因为在命令提示符窗口中,这些文本输出会

一闪而过。

你可以根据自己的偏好使用任何一种脚本处理器。在下一小节中,我将向你介绍运行脚本的几种方式。

1.6.2 运行脚本的方式

正如你所知道的,Windows 通常提供了几种方式来完成同样的事情,包括点击、双击、鼠标右键点击

或拖动对象等。对于运行脚本来说,肯定也是如此。有 6 种方式开始运行一个脚本文件,如表 1-3 所示。

表 1-3 运行脚本文件的方式

操  作 运行模式

 在 Windows 资源管理器、一个 Find Files 窗口中、或桌面,双击文件(在 Windows Vista 上,可

能会出现一个安全警告;点击 Open 来运 行一个脚本,我们将在稍后介绍)默认宿主

 鼠标右键点击文件并选择 Open(打开) Wscript

 鼠标右键点击文件并选择 Open with Command Prompt(在命令提示符中打开) Cscript

 在命令提示符窗口中、在 Windows 7/Vista Start 菜单的搜索框中、在 Run 对话框中,或在一种

快捷方式中,输入脚本文件的名称① 默认宿主

 在一个命令提示符窗口中,在 Start、Run 对话框中,或在一种快捷方式中,输入 cscript 或wscript,后面跟着脚本② 指定宿主

 拖动一个或多个文件,并且将其放置到 Windows 资源管理器或桌面上的脚本文件的图标上 默认宿主

① 在 Windows 7、Vista、XP、NT 和 2000 中,不需要输入脚本文件的扩展名(.vbs、pl 或任何其他的),你可以直

接输入文件的基本名称。如果你仍然使用 Windows 95、98 或 Me,文件名必须包含扩展名。

② 当你通过名称显式地运行 Wscript 或 Cscript 的时候,必须总是包含脚本的扩展名。

提示 你应该现在在自己的计算机上尝试这些方法中的每一种,使用我在本章前面录入的 firstscript.vbs示例脚本。

注意,鼠标右键点击“wscript”和“cscript”方法会选择一个特定的宿主,要么是 Wscript,或者是

Cscript。其他三种方法则使用了默认宿主,这是你可以修改的一个设置。最初,Windows 使用 Wscript 作为

默认宿主。如果你愿意,可以通过在一个命令提示符窗口中输入如下这些命令之一,来修改默认宿主:

Page 15: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 15 

• wscript //H:wscript 将默认宿主设置为 Wscript。• wscript //H:cscript 将默认宿主设置为 Cscript。通常,在开发新脚本的过程中,命令行版本(Cscript)可能是最有用的,因为你可能想要让自己的脚本

显示出调试提示,以帮助理解它在做什么。记住,即便在将 cscript 设置为默认宿主以后,你总是可以对单个

脚本使用强制运行方式;可以用鼠标右键点击的方法或者显式地输入 cscript 或 wscript 命令来运行该脚本。

注意 在本章剩余的部分中,我介绍了关于 WSH 如何启动以及如何与其通信的更多细节。如果你是脚

本和编程的新手,可略过本章剩下的内容,以了解第 2 章将要介绍和延续什么内容。本章后续的内容

相当高级,需要对 VBScript 有了一些更多的经验之后,才能更好地理解。

1.6.3 给脚本传递信息

用来启动 Wscript 或 Cscript 的命令行可能来自于一个快捷方式,来自 Start、Run(开始—运行)对话框,

或者来自你在命令提示符窗口的手动输入。如果脚本是自包含的(也就是说,拥有了执行其任务所需的所

有信息),你可以直接输入脚本的文件名。

然而,以一种更加通用的方式来编写一段脚本,并且当你运行该脚本的时候再指定某些信息,这通常

是较为有用的。本章前面的示例脚本提供了一个例子 :对于要计算其中的文件的大小的文件夹,其名称是

构建到脚本之中的。如果我们可以在运行脚本的时候告诉它要查看哪个文件夹,这可能会更有用 ;通过这

种方式,我们可以使用同样的脚本来计算任何文件夹中的文件大小。

做到这一点的一种方式是,让脚本提示(或要求)用户输入任何想要的信息。我们将在第 2 章讨论如

何做到这点。

另一种技术是,当运行脚本的时候,在命令行指定这样的信息。用计算机术语来说,传递给脚本文件

这样的一个过程的信息,叫做参数。在如下的命令行中,myscript.vbs 和 c:\windows 是传递给程序 wscript的两个参数:

31How Windows Runs Scripts

Passing Information to ScriptsThe command line used to start up Wscript or Cscript can come from a shortcut;from the Start, Run dialog box; or from your own fingers typing away at the com-mand prompt. If the script is self-contained (that is, has all the information it needs toperform its job), you can simply enter the script’s filename.

However, it’s often useful to write a script in a more generic way and to specify someinformation at the time you run the script. Our sample script earlier in the chapterprovides a good example:The name of the folder whose files are to be sized is built into the script. It would be much more useful if we could tell it which folder to exam-ine when we ran it; this way, we could use the same script to count any folder’s files.

One way to do this is to have the script prompt (or ask) the user to type in anydesired information.We discuss how this is done in Chapter 2.

Another technique is to specify such information on the command line when you runthe script. In computer jargon, bits of information passed to a procedure such as ascript file are called arguments. In the following command line, myscript.vbs andc:\windows are two arguments being given to the program wscript:

wscript myscript.vbs c:\windows

In a wscript command line, arguments starting with two slashes (//) control the actionof wscript itself and the first filename argument is the name of the script to run.Anyother arguments are passed along to the script file for it to interpret as it sees fit.Thereis no predetermined meaning to arguments; it’s up to the script’s programmer todetermine whether they are to be used and how they affect the script. In one script,the extra command-line arguments might be used to indicate the names of folders todelete. In another, they might enable or disable functions that the script performs.

Each scripting language has its own way of getting argument information passedthrough its command line. If you’re familiar with writing DOS batch files, you mightremember that wherever “%1” appears in a batch file, it is replaced with the first com-mand-line argument.WSH makes the command-line arguments available through theuse of a feature called the WScript object, which I discuss in detail in Chapter 3. InVBScript, the first argument typed on the command line after the script’s name isWScript.Arguments(0).The second is WScript.Arguments(1), and so on. For example,the statement

dir = WScript.Arguments(0)

assigns the first argument to the variable dir.

NoteThis use of WScript in WScript.echo and WScript.Arguments, by the way, is always WScript,regardless of whether you’re running the script with wscript or cscript. Here, WScript refers to thename of an object provided by the script host, and it is named WScript, regardless of which version isrunning. Yes, it’s confusing.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 31

在一个 wscript 命令行中,参数以两个斜线(//)打头,它控制了 wscript 自身的操作,并且,第一个文

件名参数是要运行的脚本的名称。传递给脚本文件的任何其他参数,将按照该脚本认为合适的方式来解释。

参数没有预先确定的含义 ;由脚本的程序员来确定是否使用它们以及它们如何影响到脚本。在一个脚本中,

额外的命令行参数可以用来表示要删除的文件夹的名称。在另一个脚本中,它们可能打开或关闭脚本所执

行的功能。

每种脚本语言都有自己的方式来获取通过其命令行传递的参数信息。如果你熟悉编写 DOS 批处理文

件,你可能记得,无论“%1”出现在一个批处理文件中的何处,都会用第一个命令行参数来替换它。WSH通过使用叫做 WScript 对象的一种功能,来使得命令行参数可用,我们将在第 3 章中介绍这一功能。在

VBScript 中,在命令行中位于脚本名称之后的第一个参数是 WScript.Arguments(0),第二个参数是 WScript.Arguments(1),依次类推。例如,语句

31How Windows Runs Scripts

Passing Information to ScriptsThe command line used to start up Wscript or Cscript can come from a shortcut;from the Start, Run dialog box; or from your own fingers typing away at the com-mand prompt. If the script is self-contained (that is, has all the information it needs toperform its job), you can simply enter the script’s filename.

However, it’s often useful to write a script in a more generic way and to specify someinformation at the time you run the script. Our sample script earlier in the chapterprovides a good example:The name of the folder whose files are to be sized is built into the script. It would be much more useful if we could tell it which folder to exam-ine when we ran it; this way, we could use the same script to count any folder’s files.

One way to do this is to have the script prompt (or ask) the user to type in anydesired information.We discuss how this is done in Chapter 2.

Another technique is to specify such information on the command line when you runthe script. In computer jargon, bits of information passed to a procedure such as ascript file are called arguments. In the following command line, myscript.vbs andc:\windows are two arguments being given to the program wscript:

wscript myscript.vbs c:\windows

In a wscript command line, arguments starting with two slashes (//) control the actionof wscript itself and the first filename argument is the name of the script to run.Anyother arguments are passed along to the script file for it to interpret as it sees fit.Thereis no predetermined meaning to arguments; it’s up to the script’s programmer todetermine whether they are to be used and how they affect the script. In one script,the extra command-line arguments might be used to indicate the names of folders todelete. In another, they might enable or disable functions that the script performs.

Each scripting language has its own way of getting argument information passedthrough its command line. If you’re familiar with writing DOS batch files, you mightremember that wherever “%1” appears in a batch file, it is replaced with the first com-mand-line argument.WSH makes the command-line arguments available through theuse of a feature called the WScript object, which I discuss in detail in Chapter 3. InVBScript, the first argument typed on the command line after the script’s name isWScript.Arguments(0).The second is WScript.Arguments(1), and so on. For example,the statement

dir = WScript.Arguments(0)

assigns the first argument to the variable dir.

NoteThis use of WScript in WScript.echo and WScript.Arguments, by the way, is always WScript,regardless of whether you’re running the script with wscript or cscript. Here, WScript refers to thename of an object provided by the script host, and it is named WScript, regardless of which version isrunning. Yes, it’s confusing.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 31

将第一个参数赋给了变量 dir。

注意 顺便提一下,在 WScript.echo 和 WScript.Arguments 中用到 WScript 的时候,总是使用 WScript,不管你是用 wscript 还是 cscript 来运行脚本。这里,WScript 指的是脚本宿主所提供的一个对象的名称,

并且,该对象名为 WScript,而不管运行脚本宿主的哪个版本。没错,这有些令人混淆。

我们可以利用这一点来重新编写最初的示例脚本,如下所示:

Page 16: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 16  第一部分 用 Windows Script Host 进行脚本编程 

32 Chapter 1 Windows Script Host

We could rewrite the original sample script to take advantage of this, as follows:

‘ script0102.vbs‘ total up space used in the directory named on the command line

dir = WScript.Arguments(0)

set Fsys = CreateObject(“Scripting.FileSystemObject”)totsize = 0for each file in Fsys.GetFolder(dir).Files

totsize = totsize + file.sizenextwscript.echo “The total size of the files in” , dir, “is” , totsize

Note that the only difference between this script and the earlier version is the waythat that the variable dir is set up in the third line of the script.

Now, we can type these commands at the command prompt to count the files in theTemp and Windows directories, respectively:

Script0102 c:\temp

Script0102 c:\windows

Trouble arises when we try to count a folder whose name has spaces in it. For exam-ple, I might type

Script0102 c:\Program Files\Internet Explorer

Windows considers the spaces in this long pathname to indicate that we’re specifyingthree separate arguments:

n WScript.Arguments(0) = c:\Programn WScript.Arguments(1) = Files\Internetn WScript.Arguments(2) = Explorer

The solution is to put quotes (““) around the misbehaving text, so Windows knows totreat it as one long item:

Script0102 “c:\Program Files\Internet Explorer”

Using command-line arguments in your own scripts helps you create more general-purpose, useful tools. In the examples later in this book, I show you several examplesof this.

Saving the Results from ScriptsIf you want a script to record information, rather than just have it appear on yourscreen, you have two choices.

First, you can use Cscript and have your script program display its results in the com-mand prompt window.You saw how this looks earlier in the chapter in Figure 1.5.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 32

注意,这段脚本和前面的脚本之间的唯一区别是,在脚本的第三行设置 dir 变量的方式。

现在,可以在命令提示符窗口输入如下命令,分别来计算 Temp 和 Windows 目录中的文件的大小:

32 Chapter 1 Windows Script Host

We could rewrite the original sample script to take advantage of this, as follows:

‘ script0102.vbs‘ total up space used in the directory named on the command line

dir = WScript.Arguments(0)

set Fsys = CreateObject(“Scripting.FileSystemObject”)totsize = 0for each file in Fsys.GetFolder(dir).Files

totsize = totsize + file.sizenextwscript.echo “The total size of the files in” , dir, “is” , totsize

Note that the only difference between this script and the earlier version is the waythat that the variable dir is set up in the third line of the script.

Now, we can type these commands at the command prompt to count the files in theTemp and Windows directories, respectively:

Script0102 c:\temp

Script0102 c:\windows

Trouble arises when we try to count a folder whose name has spaces in it. For exam-ple, I might type

Script0102 c:\Program Files\Internet Explorer

Windows considers the spaces in this long pathname to indicate that we’re specifyingthree separate arguments:

n WScript.Arguments(0) = c:\Programn WScript.Arguments(1) = Files\Internetn WScript.Arguments(2) = Explorer

The solution is to put quotes (““) around the misbehaving text, so Windows knows totreat it as one long item:

Script0102 “c:\Program Files\Internet Explorer”

Using command-line arguments in your own scripts helps you create more general-purpose, useful tools. In the examples later in this book, I show you several examplesof this.

Saving the Results from ScriptsIf you want a script to record information, rather than just have it appear on yourscreen, you have two choices.

First, you can use Cscript and have your script program display its results in the com-mand prompt window.You saw how this looks earlier in the chapter in Figure 1.5.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 32

当试图计算其名称中有一个空格的文件夹的时候,出麻烦了。例如,输入:

32 Chapter 1 Windows Script Host

We could rewrite the original sample script to take advantage of this, as follows:

‘ script0102.vbs‘ total up space used in the directory named on the command line

dir = WScript.Arguments(0)

set Fsys = CreateObject(“Scripting.FileSystemObject”)totsize = 0for each file in Fsys.GetFolder(dir).Files

totsize = totsize + file.sizenextwscript.echo “The total size of the files in” , dir, “is” , totsize

Note that the only difference between this script and the earlier version is the waythat that the variable dir is set up in the third line of the script.

Now, we can type these commands at the command prompt to count the files in theTemp and Windows directories, respectively:

Script0102 c:\temp

Script0102 c:\windows

Trouble arises when we try to count a folder whose name has spaces in it. For exam-ple, I might type

Script0102 c:\Program Files\Internet Explorer

Windows considers the spaces in this long pathname to indicate that we’re specifyingthree separate arguments:

n WScript.Arguments(0) = c:\Programn WScript.Arguments(1) = Files\Internetn WScript.Arguments(2) = Explorer

The solution is to put quotes (““) around the misbehaving text, so Windows knows totreat it as one long item:

Script0102 “c:\Program Files\Internet Explorer”

Using command-line arguments in your own scripts helps you create more general-purpose, useful tools. In the examples later in this book, I show you several examplesof this.

Saving the Results from ScriptsIf you want a script to record information, rather than just have it appear on yourscreen, you have two choices.

First, you can use Cscript and have your script program display its results in the com-mand prompt window.You saw how this looks earlier in the chapter in Figure 1.5.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 32

Windows 认为这个长长的路径名之间的空格表示分隔符,以为我们要指定 3 个单独的参数:

• WScript.Arguments(0) = c:\Program• WScript.Arguments(1) = Files\Internet• WScript.Arguments(2) = Explorer解决方案是给引发误解的文本加上引号(""),以便 Windows 知道将其当做长长的一项来对待,如下

所示:

32 Chapter 1 Windows Script Host

We could rewrite the original sample script to take advantage of this, as follows:

‘ script0102.vbs‘ total up space used in the directory named on the command line

dir = WScript.Arguments(0)

set Fsys = CreateObject(“Scripting.FileSystemObject”)totsize = 0for each file in Fsys.GetFolder(dir).Files

totsize = totsize + file.sizenextwscript.echo “The total size of the files in” , dir, “is” , totsize

Note that the only difference between this script and the earlier version is the waythat that the variable dir is set up in the third line of the script.

Now, we can type these commands at the command prompt to count the files in theTemp and Windows directories, respectively:

Script0102 c:\temp

Script0102 c:\windows

Trouble arises when we try to count a folder whose name has spaces in it. For exam-ple, I might type

Script0102 c:\Program Files\Internet Explorer

Windows considers the spaces in this long pathname to indicate that we’re specifyingthree separate arguments:

n WScript.Arguments(0) = c:\Programn WScript.Arguments(1) = Files\Internetn WScript.Arguments(2) = Explorer

The solution is to put quotes (““) around the misbehaving text, so Windows knows totreat it as one long item:

Script0102 “c:\Program Files\Internet Explorer”

Using command-line arguments in your own scripts helps you create more general-purpose, useful tools. In the examples later in this book, I show you several examplesof this.

Saving the Results from ScriptsIf you want a script to record information, rather than just have it appear on yourscreen, you have two choices.

First, you can use Cscript and have your script program display its results in the com-mand prompt window.You saw how this looks earlier in the chapter in Figure 1.5.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 32

在脚本中使用命令行参数,有助于创建较为通用的、有用的工具。在本书稍后部分,我将展示几个

示例。

1.6.4 保存脚本的结果

如果你想要一个脚本记录信息,而不只是让信息显示在屏幕上,有以下两个选择。

首先,你可以使用 Cscript,并且让你的脚本程序在命令提示符窗口中显示其结果。本章前面的图 1-5展示了其样子。

也可以使用输出重定向将脚本输出保存到一个文件中。如果你向任何命令行程序添加了 >somefile,其

输出将保存到名为 somefile 的文件中。然后,可以打印这个文件,用某些其他的程序来处理它,用 Notepad查看它,等等。如下是一个示例:

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

这会运行我们的示例脚本之一,并且将其结果保存到名为 wincount.txt 的文件中。你也可以通过下面的

命令,使用 Notepad 来查看结果:

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

如果你想要在命令提示符窗口中查看输出,但是太多的输出瞬间即逝而来不及阅读,你可以使用 more命令,使用管道方法(|):

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

在这种情况下,| 告诉 Windows 将脚本的输出发送给程序 more,这是 Windows 中内建的一个程序,它

Page 17: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 17 

每次显示一整屏的输出。按下空格会从一屏进入到下一屏。

保存一个脚本产生的信息的第二种方法是,在脚本中使用程序命令,让脚本程序直接创建一个文件。

我们将在第 4 章中介绍这一点。

1.6.5 Wscript 和 Cscript 命令选项

有了对命令行参数前面的介绍之后,对于能够通过命令行上的参数来控制 cscript 和 wscript 的行为,你

应该不会感到惊讶了。实际上,你可以给 wscript 或 cscript 添加几个专门的参数,以改变其行为。

Cscript 通常在每次启动的时候,在显示出你的脚本的任何输出之前,先显示出一条消息。例如,如果

我输入

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

结果应该如下所示:

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

我能够做出的一项修改是,向命令行添加 //Nologo,要注意,使用的是斜杠而不是反斜杠,如下所示:

33How Windows Runs Scripts

You can save this output to a file with output redirection. If you add >somefile to anycommand-line program, its output is saved in the file named somefile.You can thenprint this file, process it with some other program, view it with Notepad, and so on.Here’s an example:

cscript script0102.vbs c:\windows >wincount.txt

This runs one of our sample scripts and saves the results in the file namedwincount.txt.You can then view results using Notepad with this command:

notepad wincount.txt

If you want to view the output in the Command Prompt window, but too much output goes by to read at once, you can use the more command, using the pipe (|)mechanism:

cscript script0102.vbs c:\windows | more

In this case, | tells Windows to send the output of your script to the program more,which is a program built in to Windows that displays output one full screen at a time.Pressing the spacebar advances you from one screen to the next.

The second way of saving information that a script has produced is to have the scriptprogram create a file directly using program commands in the script.We discuss this inChapter 4,“File and Registry Access.”

Wscript and Cscript Command OptionsAfter the earlier discussion about command-line arguments, it shouldn’t be a surprisethat you can control the behavior of cscript and wscript through arguments on thecommand line. Indeed, you can add several special arguments to the wscript or cscriptcommand line to change its behavior.

Cscript usually prints a message every time it starts, before printing any output fromyour script. For example, if I type

cscript script0102.vbs c:\windows

the result looks something like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

The total size of the files in c:\windows is 10512614

One change I can make is to add //Nologo to the command line, being careful to useforward slashes rather than backslashes, like this:

cscript //Nologo script0102.vbs c:\windows

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 33

这会导致显示如下的输出:

34 Chapter 1 Windows Script Host

This causes the output to display as follows:

The total size of the files in c:\windows is 10512614

This is much nicer.WSH recognizes several special optional arguments, each precededby // to notify the host that the argument is for its use rather than something to begiven to the script.The complete list of command-line options is shown in Table 1.4.After the table, I show you a couple of commands you can type right now that willmake your scripting life easier.

Table 1.4 Command-Line Options for wscript and cscript

Option Effect

//H:host Sets host to be the default script from now on. Enter wscriptor cscript in place of host.

//S Saves the current settings as the default settings for this user.Anyof the other options listed in this table used along with //S will“stick” for all future runs of WSH, until you change the defaultsettings again.

//B Uses “batch” mode and suppresses any script errors and input prompts from displaying. Normally, errors in your script program cause the script to stop with an error message. //B makes it try to carry on regardless.

//D Enables Active Debugging.When this option is used, if the scriptencounters an error and you’ve installed Windows ScriptDebugger (or another Microsoft visual debugging tool, such asVisual Studio), the debugger takes over and indicates the sourceof the error.

//E:engine Uses the named language engine to process the script.Normally,WSH guesses the correct engine from the script filename:VBScript for .vbs files, JScript for .js files, and so on.Use this option only if you’re using unusual filename extensions or an unusual language that WSH can’t guess.

//I Uses Interactive mode, which is the opposite of the batch modediscussed earlier. Because //I is the default setting, you need touse this option only if you previously changed the default using//S //B.

//Job:jobname Runs the script job named jobname from within a .WSF file.WSF files were discussed earlier in the chapter.

//Logo Displays the WSH copyright and version information. (This isthe default unless you use //Nologo or change the setting per-manently with //S //Nologo.)

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 34

这要好看多了。WSH 识别几个特殊的选项参数,每一个前面都有 //,以通知宿主该参数是供其使用而

不是给脚本的内容。命令行选项的完整列表如表 1-4 所示。在表的后面,我给出了一些命令,你可以立即

使用它们来使脚本编程更轻松。

表 1-4  wscript 和 cscript 的命令行选项

选  项 效  果

//H:host  将 host 设置为从现在开始的默认脚本。输入 wscript 或 csript 来替代 host

//S  保存当前的设置作为该用户的默认设置。本表中列出的任何其他选项与 //S 一起使用的话,都将

针对 WSH 将来的所有运行而“保持”,直到你再次修改默认设置

//B  使用批处理(batch)模式并不显示任何脚本错误或输出提示。通常,脚本程序中的错误会导致脚

本停止,并带有一条错误消息。//B 使得脚本无论如何都尝试执行

//D 启用 Active Debugging(打开调试器)。当使用这一选项的时候,如果脚本遇到一个错误,并且你

安装了 Windows 脚本调试器(或者其他的 Microsoft 可视化调试工具,例如 Visual Studio),调试器

会接管并指示出错误的源头

//E:engine 使用指定的语言引擎来处理脚本。通常,WSH 通过脚本文件名(对于 VBScript 来说是 vbs,对

于 JScript 来说是 .js 等)来猜测正确的引擎。如果你使用不常用的文件名扩展,或者使用 WSH 无

法猜测的一种不常用的语言,只有这时候才使用这一选项

//I  用户交互模式,这与上面提到的批处理模式相对。由于 //I 是默认的设置,只有当你之前使用 //S //B 修改过默认设置的时候,才需要使用这一选项

//Job:jobname  运行一个 .WSF 文件中名称为 jobname 的 job。WSF 文件在本章前面介绍过

//Logo  显示 WSH 的版权和版本信息(这是默认的,除非你使用 //Nologo 或使用 //S //Nologo 持久地修改

该设置)

//Nologo  不显示版权和版本信息

Page 18: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 18  第一部分 用 Windows Script Host 进行脚本编程 

选  项 效  果

//T:nn 设置允许脚本运行的最长时间为 nn 秒。例如,//T:5 意味着如果脚本运行时间超过 5 秒钟的话,它将会停止。如果当某些地方出错,而你的脚本可能试图永久运行的话,这个选项很有用

//X  在调试器中执行脚本。我将会在随后的 1.9 节中介绍这一选项

//U  只和 cscript 一起使用。告诉 cscript 编写 Unicode 数据而不是 ASCII 数据以进行输出。你可能不

需要使用这一选项

提示 没有必要记住这个列表。在命令提示符窗口中,可以输入 cscript /? 或 wscript /?,程序将会显

示有效选项的列表。如果你在命令行的某条命令之后输入 /? 的话,大多数 Windows 程序都会显示出其

有效选项的列表。

现在,我建议你利用这些选项使得 WSH 更容易使用一些。

首先,关闭每次运行 cscript 的时候都会显示的版本文本,也就是如下所示的内容:

35How Windows Runs Scripts

Option Effect

//Nologo Suppresses printout of the copyright and version.

//T:nn Sets the maximum time the script is permitted to run to nn sec-onds. For example, //T:5 means that the script will be stoppedif it takes more than 5 seconds to run.This is useful if your scriptmight “stick” or try to run forever when something goes wrong.

//X Executes the script in the debugger. I discuss this option later in the section “Debugging Scripts.”

//U Used with cscript only.Tells cscript to write Unicode datainstead of ASCII data to the output.You probably never need touse this option.

TipThere’s no need to memorize this list. At the command prompt, you can type cscript /? or

wscript /? and the program displays the list of valid options. Most Windows programs do this

if you put /? on the command line.

Right now, I recommend you take advantage of these options to make WSH a littleeasier to use.

First, turn off the version text that cscript prints every time you run it—the stuff thatlooks like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

To get rid of this, open a command prompt window and type

cscript //nologo //s

The //nologo runs cscript without that version text, and //s makes the setting permanent.

Then, if you want to work primarily with cscript, and if you want just type a script’sname on the command line and have it run with cscript by default, type this com-mand:

cscript //h:cscript

If you want some more information about cscript and wscript command-line options,read on; otherwise, you can skip ahead to the next section.

Let’s look at some examples of using the other options. I discussed the //S and //Hoptions.The other options usually change WSH’s behavior only when they’re used ona given command line. Here’s an example:

cscript somescript.vbs //T:5 //B some arguments for the script

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 35

要去除这些信息这些,打开一个命令提示符窗口,并输入:

35How Windows Runs Scripts

Option Effect

//Nologo Suppresses printout of the copyright and version.

//T:nn Sets the maximum time the script is permitted to run to nn sec-onds. For example, //T:5 means that the script will be stoppedif it takes more than 5 seconds to run.This is useful if your scriptmight “stick” or try to run forever when something goes wrong.

//X Executes the script in the debugger. I discuss this option later in the section “Debugging Scripts.”

//U Used with cscript only.Tells cscript to write Unicode datainstead of ASCII data to the output.You probably never need touse this option.

TipThere’s no need to memorize this list. At the command prompt, you can type cscript /? or

wscript /? and the program displays the list of valid options. Most Windows programs do this

if you put /? on the command line.

Right now, I recommend you take advantage of these options to make WSH a littleeasier to use.

First, turn off the version text that cscript prints every time you run it—the stuff thatlooks like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

To get rid of this, open a command prompt window and type

cscript //nologo //s

The //nologo runs cscript without that version text, and //s makes the setting permanent.

Then, if you want to work primarily with cscript, and if you want just type a script’sname on the command line and have it run with cscript by default, type this com-mand:

cscript //h:cscript

If you want some more information about cscript and wscript command-line options,read on; otherwise, you can skip ahead to the next section.

Let’s look at some examples of using the other options. I discussed the //S and //Hoptions.The other options usually change WSH’s behavior only when they’re used ona given command line. Here’s an example:

cscript somescript.vbs //T:5 //B some arguments for the script

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 35

//nologo 运行 cscript 而不显示版本文本,并且,//s 使得这一设置持久化。

然后,如果你想主要使用 cscript,并且如果想要在命令行中输入一个脚本名称,就默认地使用 cscript来运行它,可以输入如下的命令:

35How Windows Runs Scripts

Option Effect

//Nologo Suppresses printout of the copyright and version.

//T:nn Sets the maximum time the script is permitted to run to nn sec-onds. For example, //T:5 means that the script will be stoppedif it takes more than 5 seconds to run.This is useful if your scriptmight “stick” or try to run forever when something goes wrong.

//X Executes the script in the debugger. I discuss this option later in the section “Debugging Scripts.”

//U Used with cscript only.Tells cscript to write Unicode datainstead of ASCII data to the output.You probably never need touse this option.

TipThere’s no need to memorize this list. At the command prompt, you can type cscript /? or

wscript /? and the program displays the list of valid options. Most Windows programs do this

if you put /? on the command line.

Right now, I recommend you take advantage of these options to make WSH a littleeasier to use.

First, turn off the version text that cscript prints every time you run it—the stuff thatlooks like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

To get rid of this, open a command prompt window and type

cscript //nologo //s

The //nologo runs cscript without that version text, and //s makes the setting permanent.

Then, if you want to work primarily with cscript, and if you want just type a script’sname on the command line and have it run with cscript by default, type this com-mand:

cscript //h:cscript

If you want some more information about cscript and wscript command-line options,read on; otherwise, you can skip ahead to the next section.

Let’s look at some examples of using the other options. I discussed the //S and //Hoptions.The other options usually change WSH’s behavior only when they’re used ona given command line. Here’s an example:

cscript somescript.vbs //T:5 //B some arguments for the script

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 35

如果想要了解关于 cscript 和 wscript 命令行选项的更多信息,请继续阅读;否则,你可以跳转到下一

小节。

让我们来看看使用其他选项的一些示例。我介绍了 //S 和 //H 选项。其他的选项,通常只有运用于一个

给定的命令行的时候,才会改变 WSH 的行为。下面是一个示例:

35How Windows Runs Scripts

Option Effect

//Nologo Suppresses printout of the copyright and version.

//T:nn Sets the maximum time the script is permitted to run to nn sec-onds. For example, //T:5 means that the script will be stoppedif it takes more than 5 seconds to run.This is useful if your scriptmight “stick” or try to run forever when something goes wrong.

//X Executes the script in the debugger. I discuss this option later in the section “Debugging Scripts.”

//U Used with cscript only.Tells cscript to write Unicode datainstead of ASCII data to the output.You probably never need touse this option.

TipThere’s no need to memorize this list. At the command prompt, you can type cscript /? or

wscript /? and the program displays the list of valid options. Most Windows programs do this

if you put /? on the command line.

Right now, I recommend you take advantage of these options to make WSH a littleeasier to use.

First, turn off the version text that cscript prints every time you run it—the stuff thatlooks like this:

Microsoft (R) Windows Script Host Version 5.7Copyright (C) Microsoft Corporation. All rights reserved.

To get rid of this, open a command prompt window and type

cscript //nologo //s

The //nologo runs cscript without that version text, and //s makes the setting permanent.

Then, if you want to work primarily with cscript, and if you want just type a script’sname on the command line and have it run with cscript by default, type this com-mand:

cscript //h:cscript

If you want some more information about cscript and wscript command-line options,read on; otherwise, you can skip ahead to the next section.

Let’s look at some examples of using the other options. I discussed the //S and //Hoptions.The other options usually change WSH’s behavior only when they’re used ona given command line. Here’s an example:

cscript somescript.vbs //T:5 //B some arguments for the script

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 35

这告诉 cscript 运行 somescript.vbs 最长 5 秒钟的时间,并且,即便有错误也不停止。其他的参数传递给

了脚本。

//S 选项,使得其他的选项成为持久性的,就好像 //H 是持久性的一样。如果你想要持久性地关闭版权

和版本显示,如下的命令可以做到这一点:

36 Chapter 1 Windows Script Host

This tells cscript to run script somescript.vbs for a maximum of 5 seconds and not tostop even if there are errors.The other arguments are passed along to the script.

The //S option, though, makes the other options stick permanently, just as the //H ispermanent. If I want to turn off the copyright and version printout that appears everytime on a permanent basis, this command does the trick:

cscript //Nologo //S

The //S argument makes the //Nologo option stick.

NoteCapitalization doesn’t matter when using these options. For example, //T:5 and //t:5 have the

same effect.

For Registry Wonks Only…If you’re a Windows Registry guru, you might want to know where WSH setup information is stored. The

//S switch saves preference values in the Registry under HKEY_CURRENT_USER\Software\

Microsoft\Windows Script Host\Settings.

The default engine (//H) option changes the default value of keys HKEY_CURRENT_USER\Software\

Classes\xxx\Shell where xxx stands for JSFile, VBSFile, WSHFile, and other script file types. The

default value is set to open or open2, corresponding to the verbs listed under HKEY_CLASSES_ROOT\

xxx\Shell.

The actual script interpreters (engines) are DLLs registered under HKEY_CLASSES_ROOT\CLSID under

the CLSID associated with the script engine entries (for example, HKEY_CLASSES_ROOT\VBScript).

The script engine file type and engine CLSID keys are marked with a subkey named OLEScript.

The //E switch sets the engine associations by changing the Command key under HKEY_CLASSES_

ROOT\xxx\Shell\Open for each associated script file type. The list of registered script file types is

under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Scripting Host\Script

Extensions. (Notice the ing there). This setting requires Administrator privileges, but not elevated

privileges, to change.

Running Your Own ScriptsAs you develop scripts you use regularly, you can make them easy to locate and run ifyou know some tricks of the trade. I show you these tricks in this section.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 36

//S 参数使得 //Nologo 选项持久化。

注意 在使用这些选项的时候,大小写无关紧要。例如,//T:5 和 //t:5 具有相同的效果。

仅适用于注册表高手

如果你是一位 Windows 注册表高手,你可能想要知道 WSH 设置信息存储在何处。//S 开关将偏好

值存储在注册表中的 HKEY_CURRENT_USER\Software\Microsoft\Windows Script Host\Settings 之下。

默认引擎选项(//H)修改了键 HKEY_CURRENT_USER\Software\Classes\xxx\Shell 中的默认值,

其中,xxx 表示 JSFile、VBSFile、WSHFile 以及其他的脚本文件类型。默认值设置为 open 或 open2,

(续)  

Page 19: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 19 

对应于 HKEY_CLASSES_ROOT\xxx\Shell 下列出的动词。

实际的脚本解释器(引擎)是在 HKEY_CLASSES_ROOT\CLSID 下注册的 DLL,CLSID 与脚本引

擎项(例如,HKEY_CLASSES_ROOT\VBScript)相关。脚本引擎文件类型和引擎 CLSID 键,是用一

个名为 OLEScript 的子键来标记的。

//E 开关通过针对每种相关的脚本文件类型来修改 HKEY_CLASSES_ROOT\xxx\Shell\Open,从而

设置引擎关联。注册的脚本文件的类型的列表,位于 HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Scripting Host\ScriptExtensions 下(注意这里的 ing)。要修改这一设置,需要管理员权限,但

不能是提升的权限。

1.7 运行自己的脚本

在你开发自己经常使用的脚本时,如果知道一些技巧的话,可以更容易找到并运行它们。我将在本节

中介绍这些技巧。

1.7.1 将脚本添加到路径

正如我在前面所提到的,当你编写通用目的的脚本时,将其放入到一个单独的文件夹中,这是好办法,

要创建一个脚本文件夹,参见前面 1.5.1 节的说明。

然后,可以将你的脚本文件夹放入到 Windows 的 PATH 列表中,这是当你在命令提示符窗口、在

Windows XP 的 Run(运行)对话框以及 Vista 的开始菜单的搜索框中输入一个名称的时候,Windows 会搜

索文件夹的列表。如果你将自己的脚本文件夹添加到了 PATH 中,你可以随时从任何文件夹来运行一个脚

本,只需要输入其名称就可以了。

在下面的说明中,我假设你的脚本文件夹是 c:\scripts。你也可以在自己的个人配置文件夹中创建你的

脚本文件夹,例如,c:\Users\youraccount\scripts。如果你使用一个不同的位置,在后续的指令中,用该文件

夹名称替代 c:\scripts。根据你的偏好,可以针对计算机的用户或只是你自己的用户账户,将该文件夹放入到 PATH 列表中。

注意 在做了这些修改之后,关闭已经打开的命令提示符窗口。这一修改只是会影响到新的命令提示符窗口。

Windows 7 和 Vista 上,脚本对所有用户可用

要在 Windows 7 和 Vista 上,针对所有用户将你的脚本文件夹添加到 PATH 中,按照如下步骤进行:

1. 点击 Start(开始),鼠标右键点击 Computer(计算机),并且选择 Properties(属性)。

2. 点击 Advanced System Settings(高级系统设置)。

3. 点击 Environment Variables(环境变量)按钮。

4. 在对话框中找到 PATH 项,并且双击它。

5. 在 Variable Value(变量值)字段中点击。按下 End 键,输入一个分号(;),然后,在分号的后面输

入 c:\scripts。6. 点击 OK(确定)以关闭对话框。

Windows 7 和 Vista 上,脚本只对你可用

要仅针对你的用户账户将脚本文件夹添加到 PATH,按照如下的步骤:

1. 点击 Start(开始)、Control Panel(控制面板)、User Accounts and Family Safety(用户账户和家庭安全)、

User Accounts(用户账户)。

2. 在 Task list(任务列表)的底部,选择 Change My Environment Variables(更改我的环境变量)。

3. 在对话框的上部,如果有一个已有的 PATH 项,双击它。在 Variable Value(值)字段点击,按下

Page 20: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 20  第一部分 用 Windows Script Host 进行脚本编程 

End 键,输入一个分号(;),然后,在分号的后面输入 c:\scripts。否则,如果上部的列表中没有 PATH 项,点击 New(新建),输入 PATH 作为 Variable Name(变量),

然后在 Variable Value(值)字段输入 c:\scripts。4. 点击 OK(确定)以关闭对话框。

Windows XP,脚本对所有用户可用

要在 XP 上,针对所有用户将脚本文件夹添加到 PATH 中,按照如下步骤进行:

1. 作为计算机管理员登录。

2. 点击 Start(开始),鼠标右键点击 My Computer(我的电脑),并选择 Properties(属性)。

3. 选择 Advanced(高级)标签,并且点击 Environment Variables(环境变量)。

4. 在对话框靠下的位置找到 PATH 项,并双击它。

5. 在 Variable Value(值)字段中点击。按下 End 键,输入一个分号(;),然后,在分号的后面输入

c:\scripts。6. 点击 OK 以关闭对话框。

Windows XP 上,脚本只对你可用

要在 XP 上仅针对你的用户账户将脚本文件夹添加到 PATH,按照如下的步骤:

1. 点击 Start(开始),鼠标右键点击 My Computer(我的电脑),并选择 Properties(属性)。

2. 选择 Advanced(高级)标签,并且点击 Environment Variables(环境变量)。

3. 在对话框的上部,如果有一个已有的 PATH 项,双击它。在 Variable Value(值)字段点击,按下

End 键,输入一个分号(;),然后,在分号的后面输入 c:\scripts。否则,如果上部的列表中没有 PATH 项,点击 New(新建),输入 PATH 作为 Variable Name(变量),

然后在 Variable Value(值)字段输入 c:\scripts。4. 点击 OK(确定)以关闭对话框。

在设置了 PATH 列表之后,所要做的只是在命令提示符窗口、Run 对话框或 Search 对话框中输入你

的任何脚本文件的名称,Windows 将会找到该脚本。为了尝试一下,打开一个新的命令提示符窗口,输入

firstscript,并按下回车键。你的示例脚本将会运行。

1.7.2 用一个快捷方式图标来运行脚本

如果你有一个经常使用的脚本并且通过 wscript 来运行它,我建议你为该脚本文件创建一个快捷方式。

提示 如果你在一个局域网络上使用脚本,我建议将常用的脚本存储在一个共享的网络文件夹中。这

样,你可以在任何联网的计算机上创建快捷方式。当你创建了快捷方式,输入脚本的通用命名规则

(Universal Naming Convention,UNC)路径名,例如,\\bali\scripts\myscript.vbs。或者,你可以使用

Browse 在 My Network Places 下找到共享的文件。将快捷方式本身复制到一个共享的文件夹,这也很

容易。然后,你可以只是将这些快捷方式拖动到任何联网的计算机,而不需要重新创建它们。

1.7.3 制作一个脚本快捷方式

可以将一个频繁使用的脚本的快捷方式放到桌面上,放在文件夹中,放到你的 Start(开始)菜单中,

或者放到 Quick Launch(快速启动)工具栏。然而,通常只有在用 wscript 运行脚本或者脚本不产生输出的

时候,这么做才是有用的。如果你对 cscript(命令行版本)方式运行的脚本使用一个快捷方式,只要脚本

一完成,其窗口就会关闭,你没有机会看到结果。

要为一个脚本文件生成快捷方式,按照如下步骤进行:

1. 鼠标右键点击桌面并选择 New(新建)、Shortcut(快捷方式)。

Page 21: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 21 

2. 点击 Browse(浏览)并找到你的脚本文件。点击 OK(确定)。

3. 将光标移动到位置框的开始处,并且在路径和文件名的前面添加 wscript。确保在 wscript 的后面添加

一个空格。点击 Next(下一步)。

4. 将 wscript.exe 的说明修改为某些合理描述脚本功能的内容,例如 Count File Sizes。点击 Finish(完成)。

然后,可以将这一快捷方式拖放到想要放置的任何位置,包括放入 Start(开始)菜单、Quick Launch(快

速启动)工具栏,或者其他的任何地方。双击快捷方式,就可以轻易地运行该脚本。

提示 可以拖动一个或多个文件,并将它们放置到一个脚本快捷方式上。这会使用传递给脚本的每个

文件的完整路径名作为参数,来运行该脚本。可以对发送电子邮件、打印或执行其他文件相关任务的

脚本这么做。

1.7.4 从批处理文件运行脚本

你还可以通过批处理文件来运行脚本。这听起来很奇怪,但是,这会很方便。当你需要将几个程序

依次串联起来的时候,批处理文件很有用,并且,脚本文件完全可以作为这些程序之一。Windows 网络

管理员可能也想要通过批处理文件来运行脚本,将此作为一个登录脚本的一部分,我们将在第 9 章中介

绍这一点。

在一个批处理文件中,可以使用 wscript 或 cscript 来运行一个脚本。两种版本都可以通过 errorlevel 环境变量,将成功 / 失败信息传递回批处理文件,如下面的示例所示:

40 Chapter 1 Windows Script Host

You can use either wscript or cscript to run a script in a batch file. Both versions can communicate success/failure information back to the batch file through theerrorlevel environment variable, as shown in the following example:

badscript.vbs:Wscript.echo “Oops, I’ve run into a problem.”WScript.Quit(1)

runbad.bat:@echo offwscript badscript.vbsecho Wscript returned %errorlevel%if errorlevel 1 echo The script reported an error!

NoteYou might run into articles on the Web claiming that Wscript doesn’t set errorlevel, but that

information is obsolete. Versions of Wscript and Cscript since Windows 2000 do properly set the

errorlevel value.

Running Scripts AutomaticallyYou can instruct Windows to run scripts automatically when you log on, log off, atscheduled intervals, or based on other system events. For information on automaticscripting, see Chapter 9.

Security ConcernsBecause Windows has a default file-type association between the filename extensionsused by scripts (for example, .vbs and .js) and WSH, when you ask Windows to“start” or “open” a VBS file, it knows it’s a script and runs it.

This makes using scripts easy, but it can also be a security risk, and there are two rea-sons you might want to change the default behavior:

n Because scripts can be written to erase files and perform serious operating sys-tem changes, you might consider it too dangerous to make it this easy to runscripts on your computer.

n Hackers have exploited the willingness of Windows to run scripts by writingvirus and worm scripts and sending them as email attachments. If a mail recipi-ent opens the attachment and Windows is set to automatically run VBS fileswith WSH, the virus starts and does its damage.

Because you can always run scripts by explicitly typing the wscript or cscript com-mand and because you can explicitly put the word wscript or cscript before the

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 40

40 Chapter 1 Windows Script Host

You can use either wscript or cscript to run a script in a batch file. Both versions can communicate success/failure information back to the batch file through theerrorlevel environment variable, as shown in the following example:

badscript.vbs:Wscript.echo “Oops, I’ve run into a problem.”WScript.Quit(1)

runbad.bat:@echo offwscript badscript.vbsecho Wscript returned %errorlevel%if errorlevel 1 echo The script reported an error!

NoteYou might run into articles on the Web claiming that Wscript doesn’t set errorlevel, but that

information is obsolete. Versions of Wscript and Cscript since Windows 2000 do properly set the

errorlevel value.

Running Scripts AutomaticallyYou can instruct Windows to run scripts automatically when you log on, log off, atscheduled intervals, or based on other system events. For information on automaticscripting, see Chapter 9.

Security ConcernsBecause Windows has a default file-type association between the filename extensionsused by scripts (for example, .vbs and .js) and WSH, when you ask Windows to“start” or “open” a VBS file, it knows it’s a script and runs it.

This makes using scripts easy, but it can also be a security risk, and there are two rea-sons you might want to change the default behavior:

n Because scripts can be written to erase files and perform serious operating sys-tem changes, you might consider it too dangerous to make it this easy to runscripts on your computer.

n Hackers have exploited the willingness of Windows to run scripts by writingvirus and worm scripts and sending them as email attachments. If a mail recipi-ent opens the attachment and Windows is set to automatically run VBS fileswith WSH, the virus starts and does its damage.

Because you can always run scripts by explicitly typing the wscript or cscript com-mand and because you can explicitly put the word wscript or cscript before the

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 40

注意 你可能会在 Web 上遇到这样的文章,声称 Wscript 没有设置 errorlevel,但这样的信息已经过时

了。从 Windows 2000 开始,Wscript 和 Cscript 的版本都能够正确地设置 errorleve 值。

1.7.5 自动运行脚本

你可以让 Windows 在你登录时、退出时、以规定的时间间隔,或者根据其他系统事件来自动地运行脚

本。要了解关于自动脚本的信息,参见第 9 章。

1.8 安全问题

由于 Windows 在脚本所使用的文件名扩展(例如,.vbs 和 .js)和 WSH 之间有一个默认的文件类型关

联,当你要求 Windows 去“启动”或“打开”一个 VBS 文件,它知道这是脚本并且会运行它。

这使得使用脚本很容易,但同时也会有安全风险。由于以下两个原因使你要更改这一默认的行为:

• 由于脚本可用于删除文件或执行重要的操作系统修改,你可能认为它太危险了,而不应该让其如此轻

易地在计算机上运行。

• 黑客可能会编写病毒和蠕虫脚本,将它们作为电子邮件附件发送,从而利用 Windows 来运行脚本。

如果一封 Email 的收件人打开了附件,并且 Windows 设置为自动使用 WSH 运行 VBS 文件,病毒就

会启动并开始进行破坏。

由于总是可以通过明确输入 wscript 或 cscript 命令来运行脚本,并且,由于在任何快捷方式的目标部分

Page 22: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 22  第一部分 用 Windows Script Host 进行脚本编程 

的脚本文件名之前,你可以明确地放置单词 wscript 或 cscript ;关闭脚本文件和 WSH 之间的 Windows 关联,这是很安全的,你并不会因此而失去任何重要的功能。

如果想要在 Windows 7 或 Vista 上这么做,按照下面步骤进行:

1. 点击 Start(开始)、Control Panel(控制面板)。点击绿色的 Programs(程序)标题,然后,在

Default Programs(默认程序)下,选择 Make A File Type Always Open In A Specific Program(始终使用指定

的程序打开此文件类型)。

2. 在列表中找到 .vbs。选择它,然后点击 Change Program(更改程序)。

3. 点击 Browse(浏览),然后输入 \windows\system32\notepad.exe。4. 点击 Open(打开),然后点击 OK。

5. 对于 .vbe、.js、.jse 和 .wsh 文件类型重复这些步骤。

在 Windows XP 上,按照如下步骤进行:

1. 打开 Windows 资源管理器上,然后选择 Tools(工具)、Folder(文件夹)选项。

2. 选择 File Types(文件类型)标签页。

3. 在 Extensions(扩展名)下的列表中找到 VBS,并选择它。

4. 点击 Advanced(高级)按钮,在 Actions(操作)下,选择 Open(打开)。

5. 点击已有设置下的 Edit.Write(看上去类似于 C:\WINDOWS\System32\WScript.exe “%1” %*),并且

将该项修改为如下所示:

notepad “ %1”

6. 点击确定关闭两个对话框。

7. 在 Extensions(扩展名)列表中找到 JS 并重复步骤 4 和步骤 5。之后,你会注意到,你的修改自动

应用于 JSE 和 WSF 文件。

现在,你不能通过鼠标右键点击或双击一个脚本文件图标来启动它,而必须执行如下操作之一:

• 在 Target(目标)栏中,使用 wscript 或 cscript 来创建快捷方式,正如本章前面所介绍的(当你创建

了一个脚本文件的快捷方式之后,用鼠标右键点击它,选择 Properties(属性),将光标放在 Target(目

标)字段中的文件名之前,并且,输入一个空格然后是 wscript)。• 从命令提示符窗口或 Start(开始)、Run(运行)窗口,通过输入 wscript 或 cscript,后面跟着脚本文

件名称,来运行脚本。

这不是很强的安全措施 :如果恶意脚本设法绕过这些修改而启动,它仍然能够造成破坏。一些人则更

进一步,干脆从自己的计算机删除了 cscript.exe 和 wscript.exe,或者至少更改了它们的名称。

信任策略和脚本签名

对于一个 Windows Domain 网络(即由 Windos Server 管理的一个网络)上的 Windows 7、Vista 和 XP用户,还有另一种更加强大的方法来阻止未授权的脚本运行。通过网络的 Group Policy(组策略)功能,可

以让 Windows 只运行在特定目录中找到的脚本,或者不允许运行那些没有包含有效签名的脚本,签名是一

个加密的数据块,保证了脚本文件来自于一个授权的、可信的来源。网络管理员必须保证这一授权,这称

为信任策略(Trust Policy)控制。

注意 如果一个网络管理员打开了信任策略功能,你可能不能编写和运行自己的脚本。如果你运行脚

本的时候遇到问题,请联系你的网络管理员。

我将在第 9 章详细介绍脚本安全、信任策略和脚本签名。

Page 23: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 23 

1.9 调试脚本

仅仅编写程序已经足够困难了,但是,要让它正确地工作,可能需要付出非同寻常的耐性。好在

Windows 脚本带有一个图形化调试器,它允许你看看在脚本程序运行的时候其内部发生了什么。如果在

Word、Excel、Access 或其他 Microsoft 应用程序中编写和调试宏,你可能已经遇到过可视化调试器。如果

你没有遇到过,这里给出一个简单的介绍。

如果一个脚本遇到一个明显的程序错误(例如,一个错误放置的逗号,或一个不识别的单词),WSH会报告该错误。例如,下面是带有一个严重错误的脚本:

42 Chapter 1 Windows Script Host

Trust Policy and Script SigningFor Windows 7,Vista, and XP users on a Windows Domain network (that is, a net-work that is controlled by Windows Server), there is another more powerful way toprevent unauthorized scripts from running.Through the network’s Group Policy fea-ture,Windows can be instructed only to run scripts found in specified directoriesand/or to disallow scripts that don’t contain a valid signature, which is an encrypteddata block that guarantees the script file has come from an authorized, trusted source.A network administrator must grant this authorization, called Trust Policy control.

NoteIf a network manager enables the Trust Policy feature, you might not be able to write and run your own

scripts! If you run into problems running scripts, contact your network administrator.

I discuss script security,Trust Policy, and script signing in more detail in Chapter 9.

Debugging ScriptsJust writing a program can be hard enough, but getting it to work correctly can trythe patience of a saint.Thankfully,Windows scripting comes with a graphical debuggerthat lets you see what’s happening inside your script program as it runs. If you’ve writ-ten and debugged macros in Word, Excel,Access, or other Microsoft applications,you’ve probably already encountered the visual debugger. If not, here’s a short tour.

If a script encounters a glaring programming error (for example, a misplaced commaor an unrecognized word),WSH reports the error. For example, here’s a script with aserious error:

‘ bad.vbs - a script in need of debuggingfor counter = 1 to 3

wscript.echo “Counter is now”, counternext

badcommand

wscript.echo “Got past the bad command”

VBScript does not recognize the word badcommand.What happens when you try torun this script depends on which host you’ve used.

Cscript prints an error message describing the problem and indicates which line in thefile contains the error, like so:

Counter is now 1Counter is now 2Counter is now 3D:\scripts\01\bad.vbs(7, 1) Microsoft VBScript runtime error:

Type mismatch: ‘badcommand’

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 42

VBScript 不识别单词 badcommand。当你试图运行这段脚本的时候,会发生什么,这取决于你所使用的

宿主。

Cscript 打印出一条错误消息,说明了问题,并指明文件的哪一行包含错误,如下所示:

42 Chapter 1 Windows Script Host

Trust Policy and Script SigningFor Windows 7,Vista, and XP users on a Windows Domain network (that is, a net-work that is controlled by Windows Server), there is another more powerful way toprevent unauthorized scripts from running.Through the network’s Group Policy fea-ture,Windows can be instructed only to run scripts found in specified directoriesand/or to disallow scripts that don’t contain a valid signature, which is an encrypteddata block that guarantees the script file has come from an authorized, trusted source.A network administrator must grant this authorization, called Trust Policy control.

NoteIf a network manager enables the Trust Policy feature, you might not be able to write and run your own

scripts! If you run into problems running scripts, contact your network administrator.

I discuss script security,Trust Policy, and script signing in more detail in Chapter 9.

Debugging ScriptsJust writing a program can be hard enough, but getting it to work correctly can trythe patience of a saint.Thankfully,Windows scripting comes with a graphical debuggerthat lets you see what’s happening inside your script program as it runs. If you’ve writ-ten and debugged macros in Word, Excel,Access, or other Microsoft applications,you’ve probably already encountered the visual debugger. If not, here’s a short tour.

If a script encounters a glaring programming error (for example, a misplaced commaor an unrecognized word),WSH reports the error. For example, here’s a script with aserious error:

‘ bad.vbs - a script in need of debuggingfor counter = 1 to 3

wscript.echo “Counter is now”, counternext

badcommand

wscript.echo “Got past the bad command”

VBScript does not recognize the word badcommand.What happens when you try torun this script depends on which host you’ve used.

Cscript prints an error message describing the problem and indicates which line in thefile contains the error, like so:

Counter is now 1Counter is now 2Counter is now 3D:\scripts\01\bad.vbs(7, 1) Microsoft VBScript runtime error:

Type mismatch: ‘badcommand’

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 42

图形化版本 Wscript 则会停下来并显示一个对话框,告诉你该错误,如图 1-6 所示。

在两种情况下,错误消息都告诉你 WSH 在脚本文件的第 7 行遇到了某种问题,在很多情况下,这使你

很好地接近该问题,以便可以看到并修改它。

提示 当你编辑和调试脚本的时候,如果有一个文本编辑

器可以将光标直接移动到脚本错误消息所提及的行号,这

将会是很有帮助的。Notepad 能够做到这点,技巧是:点击

Format(格式)菜单并且不要选中 Word Wrap(自动换行)。

现在,你可以通过按下 Ctrl+G 跳转到一个特定的行。输入

行号并按下回车就行了。

如果你的脚本没有像预期的一样工作,并且也没有任何

显著的输入错误,至少还没有你的脚本语言可以检测到的错

误,那么,你必须做一些检测工作。

在一些情况下,插入命令来显示程序的变量的内容和

中间结果,看看它们是否有意义,这种做法是有帮助的。例

如,在本节中使用的 bad.vbs 脚本中,随着循环的进行,我让程序显示变量 counter 的内容。有时候,这种

输出叫做跟踪,它是很有帮助的。当你知道脚本能够正常工作的时候,你总是可以删除额外的 echo 或其他

的输出命令。

这一技术有效,但是它太落后。我们已经不再处于打孔卡编程的时代了,不是吗?如果你的脚本不

能像预期的那样工作,或者如果你处在编写它的第一阶段,并且想要看看内部发生了什么,以确保它能

图 1-6  Wscript 遇到一个编程错误的时候, 显示一个对话框

Page 24: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 24  第一部分 用 Windows Script Host 进行脚本编程 

够工作,有更为现代化的工具可以用来在程序运行的时候探查其内部。这种工具叫做脚本调试器(Script Debugger)。唯一的问题是,你必须下载它,因为 Windows 没有提供它。如果你想要开发脚本,访问 www.microsoft.com,搜索 Windows Script Debugger Download,并且选中 Script Debugger for Windows NT 4.0 and Later,然后,下载并安装该程序(在 XP 上,你需要作为管理员用户登录才能安装下载的文件)。

注意 如果你安装了 Microsoft Visual Studio、.NET Studio 或 InterDev,或者安装了其他的“动态”调

试器,不要再下载 Windows Script Debugger 了,你已经有了很强大的调试器。要进行检查,创建一个

名为 test.vbs 的较小的脚本。它可能只包含一条语句,例如 x = 3。然后,输入这条命令 cscript //D //X test.vbs,并且按下回车。如果出现了一个调试窗口(或者一个让你选择调试器的对话框),说明你已经

准备好了,并且可以使用已有的调试器。如果没有调试器或对话框出现,那么,继续并下载 Microsoft Script Debugger,并且继续本节剩下的内容。

在安装了 Script Debugger 之后,可以在命令行上使用 //X,用调试器来启动一个脚本。现在,命令

44 Chapter 1 Windows Script Host

Debugger for Windows NT 4.0 and Later; then download and install the program.(On XP, you need to be logged on as a Computer Administrator user to install thedownload.)

NoteIf you have Microsoft Visual Studio, .NET Studio, or InterDev installed, or have another “Active” debugger

installed, do not download the Windows Script Debugger yet—you might already have a more powerful

debugger in place. To check, create a small script named test.vbs. It can contain just one statement, such

as x = 3. Then, type this command: cscript //D //X test.vbs and press Enter. If a debugging

window (or dialog that lets you select a debugger) appears, you’re ready to go, and you should use your

existing debugger. If no debugger or dialog appears, then go ahead and download the Microsoft Script

Debugger and continue with the rest of this section.

After Script Debugger is installed, you can use //X on the command line to start ascript using the debugger. Now, the command

cscript //X d:\scripts\01\bad.vbs

causes the debugger to appear, as shown in Figure 1.7.

Figure 1.7 The Windows Script Debugger displays the contents of your script as it runs.

As the script runs, a yellow pointer shows the next script statement that is to beprocessed. In Figure 1.7, because I’ve just started the script, the pointer is on the firstactual script command after the comment and blank line.

Now, you can walk your script through its paces one step at a time, or you can let itrun ahead to a desired point and make it stop.Although you can use the debugger’smenus to do this, you find it much easier to use if you learn the keyboard shortcuts.The most important shortcut keys are shown in Table 1.5.

02_9780789737281_ch01.qxd 11/3/10 8:19 PM Page 44

导致调试器出现了,如图 1-7 所示。

图 1-7 Windows Script Debugger 在脚本运行的时候显示其内容

在脚本运行的时候,一个黄色的指针指向了将要处理的下一条脚本语句。在图 1-7 中,由于我已经开

始运行脚本,指针位于注释和空白行之后的第一条真正的脚本命令上。

现在,你可以每次一步来步进执行脚本,或者,可以让它运行到想要的位置并让其停止下来。尽管你

可以使用调试器菜单来做到这些,可你会发现,学会键盘快捷方式的话,会更容易使用。最重要的快捷键

如表 1-5 所示。

表 1-5 Windows Script Debugger 功能键

键 动  作

F8  每次将脚本向前运行一条语句。如果脚本调用一个脚本子例程或函数,调试器“进入”到子例

程中,并且在其第一行停止

Shift+F8  类似于 F8,但是“跳过”任何子例程或函数

F9 在脚本程序行中的任何位置点击光标并按下 F9,将会在该行设置或清除一个断点。当程序运行

到标记的行的时候,断点会终止程序的运行。如果你想要看看在程序中某个位置发生了什么,并

且不想麻烦地每次一行地步进到该位置,设置一个断点并按下 F5

F5  允许程序全速运行,直到其结束、遇到一个严重错误或者遇到一个断点

Ctrl+Shift+F8  如果程序位于一个脚本子例程或函数中,脚本会运行直到子例程返回,然后结束

Page 25: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

第 1 章 Windows 脚本宿主(WSH) 25 

查看并替换变量

除了允许步进脚本,调试器还允许查看并修改脚本中的变量的内容。这是调试器最有价值的功能。点

击 View、Command Windows 来显示命令窗口,如图 1-8 所示。

Command Windows 有三个方法帮助调试程序:

• 可以通过输入一个问号,后面跟着任何变量的名称以及回车键,来显示该变量的值。在图 1-8 中,我

请求查看变量 num 的值,并且,调试器显示 1。• 可以通过输入一条赋值语句来修改一个变量的值,如图 1-8 所示,其中,我们将 num 的值从 1 更改为 4。当

你的脚本出现一个错误,并且你想要继续调试的时候,可以使用这一功能来解决这个错误。尽管不能在调

试器运行的时候修改程序本身,你还是可以更改变量并继续运行,从而从调试器会话获取更多一些的信息。

• 可以通过输入一条相应的程序语句,来调用任何子例程、函数、对象方法或属性。使用 ? 来调用并显

示函数的值,例如 ? mid(“ABC”,2)。要调用子例程,输入子例程的名称以及任何参数。在图 1-8 中,

我使用参数 num = 15 来调用子例程 shownumber。查看 Call StackCall Stack 窗口如图 1-8 所示,是帮助你监控脚本内部工作的另一个工具。要显示它,选择 View、Call

Stack。这个窗口列出了当前使用的任何子例程或函数的名称。它在顶部列出了当前子例程,后面跟着调用

它的例程的名称,以此类推,直到主脚本程序。

图 1-8  Command Window 允许你查看和修改变量,以及手动地执行程序语句。Call Stack 窗口展示了调用

子例程和函数的顺序

当调试调用了多个子例程或者使用了递归(我们将在第 4 章介绍递归技术)的脚本的时候,查看调

用栈很有用。你可以双击 Call Stack 窗口中的任何项,并且,调试器将会显示所涉及的子例程在脚本中的

位置。

尽管 Windows Script Debugger 是一款有用的工具,能够确保脚本运行完你认为它应该运行的所有步

骤,但是,如果你使用了其他的 Microsoft 产品中功能完备的调试器的话,会发现这一工具缺乏 3 项重要

的功能:

• 不能选择“下一条要运行的语句”来改变脚本处理语句的顺序(例如,跳过一个有问题的区域)。

• 如果脚本遇到一个严重错误,它会以通常的方式显示一条错误消息并停止。你不能在调试器中解决这

个问题。

Page 26: Windows 脚本宿主 WSH - Baiduimages.china-pub.com/ebook195001-200000/198705/ch01.pdf · Microsoft provides.I discuss this later in the chapter. 02_9780789737281_ch01.qxd 11/3/10

 26  第一部分 用 Windows Script Host 进行脚本编程 

• 不能编辑脚本并让调试器重新启动。你必须退出调试器并再次启动它。

好了,对免费的东西,还能有什么期望呢?当你想要了解脚本内部是如何运行的时候,它仍然是一款

有用的工具。

提示 如果你将调试输出命令放到脚本中,以显示变量的值 ;当你让脚本工作的时候,请注释这些语

句而不是删除它们。通过这种方式,如果你随后需要再次调试,可以很容易地恢复它们。

如果你安装了 Microsoft Word 或 Excel 的一个版本,可以使用内建的 Visual Basic for Applications环境来开发脚本。可以通过在菜单栏中点击 Tools、Macros、Visual Basic Editor 来找到它。在这里,你

不能访问 WScript,但是,可以在这一更为强大的调试和测试环境中开发脚本的其他方面。

提示 大多数脚本语言提供了一条特殊的命令,来激活调试器并且在遇到该命令的时候就停止脚本。

在 VBScript 中,这就是 stop 语句。在 JScript 中,是 debugger 语句。它们的作用就像是断点,只不过

它们直接构建到了脚本中,并且当你调试那些用来创建可脚本编程对象的 WSC 脚本(WSC 将在附录

G 中介绍,可以从 www.helpwin7.com/scripting 下载附录 G)的时候,它们特别方便。

1.10 到哪里获得更多信息

Web 上关于脚本编程的信息很多。尤其是,对于你想要完成的任何特定的脚本编程工作,你可能会发

现 Web 上已经有编写好的一段脚本,能够完成你需要的大部分甚至所有的工作。

了解了这一点,可参考表 1-6 中列出的站点。

表 1-6 Windows 脚本宿主的 Web 资源

Web 站点或新闻组 说  明

technet.microsoft.com/scriptcenter  Microsoft Technet Script Centet 是 WSH 的权威信息资源。它包括详细的文

档、教程和示例

www.helpwin7.com/scripting  本书中的示例脚本的下载站点

www.microsoft.public.scripting.wsh  最新的更正和提示信息

www.microsoft.public.scripting.vbscript Microsoft 提供的公开新闻组。这是查找脚本编程思路并张贴你遇到的问题

的好地方。尽管你可能不会在这里得到来自 Microsoft 职员的反馈或技术支

持,但是,该社区的访问者可能会为你解答问题和给出建议

如果你发现其他特别有用的脚本编程资源,请在 www.helpwin7.com/scripting 上留言来告诉我。