使用 WSH,可以啟動(dòng)應(yīng)用程序。下面的腳本將演示一些這樣的功能。
某些應(yīng)用程序(如 Microsoft Word)會(huì)展示可通過編程方式訪問的對(duì)象。下面的腳本將使用 Word 的拼寫檢查器。
// JScript。 var Word,Doc,Uncorrected,Corrected; var wdDialogToolsSpellingAndGrammar = 828; var wdDoNotSaveChanges = 0; Uncorrected = "Helllo world!"; Word = new ActiveXObject("Word.Application"); Doc = Word.Documents.Add(); Word.Selection.Text = Uncorrected; Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show(); if (Word.Selection.Text.length != 1) Corrected = Word.Selection.Text; else Corrected = Uncorrected; Doc.Close(wdDoNotSaveChanges); Word.Quit(); ' VBScript。 Dim Word,Doc,Uncorrected,Corrected Const wdDialogToolsSpellingAndGrammar = 828 Const wdDoNotSaveChanges = 0 Uncorrected = "Helllo world!" Set Word = CreateObject("Word.Application") Set Doc = Word.Documents.Add Word.Selection.Text = Uncorrected Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show If Len(Word.Selection.Text) <> 1 Then Corrected = Word.Selection.Text Else Corrected = Uncorrected End If Doc.Close wdDoNotSaveChanges Word.Quit
Shell.Exec 命令提供 Shell.Run 方法之外的附加功能。這些功能包括:
下面的 VBScript 示例將演示如何使用標(biāo)準(zhǔn)流和 Shell.Exec 命令在磁盤上搜索與常規(guī)表達(dá)式匹配的文件名。
首先,下面是一個(gè)小腳本,它將當(dāng)前目錄中每個(gè)文件的完整路徑都轉(zhuǎn)儲(chǔ)到 StdOut 中,如下所示:
' VBScript。 ' MYDIR.VBS Option Explicit Dim FSO Set FSO = CreateObject("Scripting.FileSystemObject") DoDir FSO.GetFolder(".") Sub DoDir(Folder) On Error Resume Next Dim File,SubFolder For Each File In Folder.Files WScript.StdOut.WriteLine File.Path Next For Each SubFolder in Folder.SubFolders DoDir SubFolder Next End Sub
接著,下面的腳本將在 StdIn 中搜索某個(gè)模式,并將所有與該模式相匹配的行都轉(zhuǎn)儲(chǔ)到 StdOut 中。
' MyGrep.VBS Option Explicit Dim RE,Line If WScript.Arguments.Count = 0 Then WScript.Quit Set RE = New RegExp RE.IgnoreCase = True RE.Pattern = WScript.Arguments(0) While Not WScript.StdIn.AtEndOfStream Line = WScript.StdIn.ReadLine If RE.Test(Line) Then WScript.StdOut.WriteLine Line WEnd
將這兩個(gè)腳本放在一起便可達(dá)成我們的目的 一個(gè)腳本列出目錄樹中的所有文件,另一個(gè)腳本查找與常規(guī)表達(dá)式匹配的行,F(xiàn)在我們編寫第三個(gè)程序來完成兩件事:它使用操作系統(tǒng)將一個(gè)程序?qū)肓硪粋(gè)程序,然后將所產(chǎn)生的結(jié)果導(dǎo)入自己的 StdOut 中:
// MyWhere.JS if (WScript.Arguments.Count() == 0) WScript.Quit(); var Pattern = WScript.Arguments(0); var Shell = new ActiveXObject("WScript.Shell"); var Pipe = Shell.Exec("%comspec% /c \"cscript //nologo mydir.vbs | cscript //nologo mygrep.vbs " + Pattern + "\""); while(!Pipe.StdOut.AtEndOfStream) WScript.StdOut.WriteLine(Pipe.StdOut.ReadLine());