发布新日志

  • Creating Additional Objects

    2010-03-23 23:19:04

    We create the wshShell object by using the following command:

    Set bjShell = createObject("wscript.shell")

     

    Once we create the wscript.shell object, we have access to the following methods:

    Method

    Purpose

    Run

    Runs an external command

    Exec

    Runs an external command, but provides access to the datastream

    appActivate

    Brings a specified window to the foreground

    sendKeys

    Enables you to send keystrokes to the foreground application

    CreateShortCut

    Creates shortcuts

    LogEvent

    Writes to the application Event log

    RegRead

    Reads from the registry

    RegWrite

    Writes to the registry

    RegDelete

    Deletes from the registry

    PopUp

    Displays a pop-up dialog box

    ExpandEnvironmentStrings

    Parses environmental variables (these variables can be displayed by using the Set command from a CMD prompt)

     

     

    CreateAddRemoveShortCut.vbs

    Option Explicit
    Dim objShell
    Dim strDesktop 'pointer to desktop special folder
    Dim objShortCut 'used to set properties of the shortcut. Comes from using createShortCut
    Dim strTarget
    strTarget = "control.exe"
    set bjShell = CreateObject("WScript.Shell")
    strDesktop = objShell.SpecialFolders("Desktop")
     
    set bjShortCut = objShell.CreateShortcut(strDesktop & "\AddRemove.lnk")
    objShortCut.TargetPath = strTarget
    objShortCut.Arguments = "appwiz.cpl"
    objShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,21"
    objShortCut.description = "addRemove"
    objShortCut.Save

     

     

     

     

    RunNetStat.vbs

    Option Explicit 'is used to force the scripter to declare variables
    'On Error Resume Next 'is used to tell vbscript. to go to the next line if it encounters an Error
    Dim objShell 'holds WshShell object
    Dim objExecObject 'holds what comes back from executing the command
    Dim strText 'holds the text stream from the exec command.
    Dim command  'the command to run 
    command = "cmd /c netstat -ano"
    WScript.Echo "starting program " & Now 'used to mark when program begins
    Set bjShell = CreateObject("WScript.Shell")
    Set bjExecObject = objShell.Exec(command)
     
    Do Until objExecObject.StdOut.AtEndOfStream
      strText = objExecObject.StdOut.ReadAll()
      WScript.Echo strText
    Loop
    WScript.echo "complete" 'lets me know program is done running

     

     

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

     

     

     


  • While...Wend

    2010-03-23 22:01:32

    While...Wend


    It is read as follows: "While statement A is true, we will continue to loop through the code. Once it is met, then we will exit at the Wend statement." It is very similar to a Do...Until loop statement.

    Example:WhileWendLoop.vbs

    Option Explicit
    'On Error Resume Next
    dim dtmTime
    
    Const hideWindow = 0
    Const sleepyTime = 1000
    dtmTime = timeSerial(19,25,00)
    while dtmTime > Time
    WScript.Echo "current time is: " & Time &_
    " counting to " & dtmTime
    WScript.Sleep sleepyTime
    Wend
    subBeep
    WScript.Echo dtmTime & " was reached."
    
    Sub subBeep
    Dim objShell
    Set bjShell = CreateObject("WScript.Shell")
    objShell.Run "%comspec% /c echo " & Chr(07),hideWindow
    End Sub


     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

  • Do...Loop

    2010-03-23 21:11:43

    Do...Loop

    The Do...Loop statement is used to put a script. into a loop for an undetermined number of loops. It causes the script. to simply loop and loop and loop

    Example:DoLoopMonitorForProcessDeletion.vbs

    Option Explicit
    'On Error Resume Next
    dim strComputer 'computer to run the script. upon.
    dim wmiNS 'the wmi namespace. Here it is the default namespace
    dim wmiQuery 'the wmi event query
    dim objWMIService 'SWbemServicesEx object
    dim colItems 'SWbemEventSource object
    dim objItem 'individual item in the collection
    Dim objName ' monitored item. Any Process.
    Dim objTGT 'monitored class. A win32_process.

    strComputer = "."
    objName = "'Notepad.exe'" 'the single quotes inside the double quotes required
    objTGT = "'win32_Process'"
    wmiNS = "\root\cimv2"
    wmiQuery = "SELECT * FROM __InstanceDeletionEvent WITHIN 10 WHERE " _
        & "TargetInstance ISA " & objTGT & " AND " _
          & "TargetInstance.Name=" & objName
    Set bjWMIService = GetObject("winmgmts:\\" & strComputer & wmiNS)
    Set colItems = objWMIService.ExecNotificationQuery(wmiQuery)
    Set bjItem = colItems.NextEvent
    Wscript.Echo "Name: " & objItem.TargetInstance.Name & " " & now
    Wscript.Echo "ProcessID: " & objItem.TargetInstance.ProcessId
    WScript.Echo "user mode time: " & objItem.TargetInstance.UserModeTime
    Loop

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

     

  • Do Until...Loop

    2010-03-23 17:46:41

    Do Until...Loop

    Do...Loop enables the script. to continue to perform. certain actions until a specific condition occurs. Do While...Loop enables your script. to continue to perform. these actions as long as the specified condition remains true. Once the specified condition is no longer true, Do While...Loop exits. In contrast, Do Until...Loop has the opposite effectthe script. continues to perform. the action until a certain condition is met.

    Example:ReadTextFile.vbs

    'header information section and on error resume next, define the variables
    Option Explicit
    On Error Resume Next
    Dim strError
    Dim objFSO
    Dim objFile
    Dim strLine
    Dim intResult

    'define the constant ForReading and strError
    CONST ForReading = 1
    strError = "Error"
    'connection filesystemobject,open the text file by forreading method
    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjFile = objFSO.OpenTextFile("C:\windows\setuplog.txt", ForReading)
    'read every line with the text
    strLine = objFile.ReadLine

    Do Until objFile.AtEndofStream
      strLine = objFile.ReadLine
      intResult = InStr(strLine, strError)
      If intResult <> 0 Then
      WScript.Echo(strLine)
      End If
    Loop
    WScript.Echo("all done")
    objFile.Close

     

      

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

     

     

  • Do While...Loop

    2010-03-23 14:14:43

    Do While...Loop

    The Do While...Loop command enables you to run a script. as long as a certain condition is in effect

     

    Example:MonitorForChangedDiskSpace.vbs

    'Header information section,define the variabl and on error resume Next
    Option Explicit
    On Error Resume Next
    Dim colMonitoredDisks
    Dim objWMIService
    Dim objDiskChange
    Dim strComputer
    Dim startTime 'snapTime used for timer Function

    'reference information secton
    Const LOCAL_HARD_DISK = 3 'the driveType value from SDK
    Const RUN_TIME = 1000 'time to allow the script. to run in seconds
    strComputer = "."
    startTime = Timer

    'Worker and Output Information section
    Set bjWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colMonitoredDisks = objWMIService.ExecNotificationQuery _
       ("Select * from __instancemodificationevent within 10 where " _
         & "TargetInstance ISA 'Win32_LogicalDisk'")
    Do While True
    snapTime = Timer
     Set bjDiskChange = colMonitoredDisks.NextEvent
      If objDiskChange.TargetInstance.DriveType = LOCAL_HARD_DISK Then
      WScript.echo "diskSpace on " &_
      objDiskChange.TargetInstance.deviceID &_
      " has changed. It now has " &_

      objDiskChange.TargetInstance.freespace &_
      " Bytes free."
      End If
      If (snapTime - startTime) > RUN_TIME Then
      Exit Do
      End If
    Loop
    WScript.Echo FormatNumber(snapTime-startTime) & " seconds elapsed. Exiting now"
    WScript.quit

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

     

     

  • For...Next

    2010-03-23 11:06:32

    For...Next VS For Each...Next

    An important difference between For Each...Next and For...Next is that with For Each...Next, you don't have to know how many times you want to do something. With the For...Next construct, you must know exactly how many times you want to do something.

     

    例子DisplayProcessInformation.vbs

    'Header information section,define the variabl and on error resume Next
    Option Explicit
    On Error Resume Next
    Dim objWMIService
    Dim objItem
    Dim i

    'reference information sectuin,define two constants
    Const MAX_LOOPS = 8, ONE_HOUR = 3600000

    'Worker and Output Information, connects to WMI and then executes a query
    'that lists all Win32 processes running on the machine
    'query chooses everything from the Win32 process, but only if the process ID is not equal to 0
    '(the system idle process)

    For i = 1 To MAX_LOOPS
    Set bjWMIService = GetObject("winmgmts:").ExecQuery _
      ("SELECT * FROM Win32_Process where processID <> 0")
    WScript.Echo "There are " & objWMIService.count &_
     " processes running " & Now
     For Each objItem In objWMIService
        WScript.Echo "Process: " & objItem.Name
        WScript.Echo Space(9) & objItem.commandline
        WScript.Echo "Process ID: " & objItem.ProcessID
        WScript.Echo "Thread Count: " & objItem.ThreadCount
        WScript.Echo "Page File Size: " & objItem.PageFileUsage
        WScript.Echo "Page Faults: " & objItem.PageFaults
        WScript.Echo "Working Set Size: " & objItem.WorkingSetSize
        WScript.Echo vbNewLine  ' add a blank line
      Next
      WScript.Echo "******PASS COMPLETE**********"
      WScript.Sleep ONE_HOUR    'wscript. sleep method, the time expression with milliseconds
    Next

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

  • Constants vs. Variables

    2010-03-22 20:33:33

    Compareing to Variable,there are several advantages by using a constant

    1 The script. is easier to read

    2 The script. is easier to revise

    3 The script. is easier to reuse

     

    Wrong example for variable

    Option Explicit
    On Error Resume Next

    Dim total
    Dim FirstValue
    Dim SecondValue

    FirstValue = 1
    SecondValue = 3
    Total = FirstValue + SecondValue

    WScript.Echo " the total of " & FirstValue & " and " & _
      SecondValue & " Is " & (total)
    FirstValue = Total
    WScript.Echo " the total of " & FirstValue & " and " & _
      SecondValue & " Is " & (Total)

     

    Executing the scripting The result is wrong like below:

    C:\script.vbs H:CScript

    Microsogt <R> Windows Script. Host Version 5.7

    Copyright <C> Microsoft Corporation. All right reserved.

    the total of 1 and 3 Is 4

    the total of 4 and 3 Is 4

     

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

  • For Each...Next

    2010-03-22 20:17:05

    例子CollectionOfDrives.vbs

    Option Explicit
    On Error Resume Next
    Dim colDrives 'the collection that comes from WMI
    Dim drive   'an individual drive in the collection
    Const DriveType = 3 'Local drives. From the SDK

    set colDrives =_
    GetObject("winmgmts:").ExecQuery("select size,freespace " &_
    "from Win32_LogicalDisk where DriveType =" & DriveType)

    For Each drive in colDrives 'walks through the collection
    WScript.Echo "Drive: " & drive.DeviceID
    WScript.Echo "Size: " & drive.size
    WScript.Echo "Freespace: " & drive.freespace
    Next

     

    For Each...Next,描述的是个体和集合的概念,只要存在集合的概念,应第一考虑For Each...Next的用法,例如

    files, and folders are returned as a collection from the fileSystemObject

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

     

     

  • VBScript Step By Step Chapter 1

    2010-03-22 19:22:02

    例1 DisplayAdminTools.vbs

    Set bjshell = CreateObject("Shell.Application")
    Set bjNS = objshell.namespace(&h2f)
    Set colitems = objNS.items
    For Each objitem In colitems
    WScript.Echo objitem.name
    Next

     

    Table 1-1. Useful registry keys for script. writers

    Information

    Location

    Service information

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

    User name used to log on to the domain

    HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Logon User Name

    Microsoft Exchange 2000 domain information

    HKEY_CURRENT_USER\Software\Microsoft\Exchange\LogonDomain

    Exchange 2000 domain user information

    HKEY_CURRENT_USER\Software\Microsoft\Exchange\UserName

    Group Policy server

    HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Group Policy\History\DCName

    User's home directory

    HKEY_CURRENT_USER\Volatile Environment\HomeShare

    The server that authenticated the currently logged-on user

    HKEY_CURRENT_USER\Volatile Environment\LOGONSERVER

    The DNS domain name of the currently logged-on user

    HKEY_CURRENT_USER\Volatile Environment\USERDNSDOMAIN



    例2 DisplayComputerNamesWithComments.vbs

    'This script. displays various Computer Names by reading the registry

    Option Explicit     'forces the scripter to declare variables
    On Error Resume Next 'tells VBScript. to go to the next line
                     'instead of exiting when an error occurs
    'Dim is used to declare variable names that are used in the script
    Dim objShell
    Dim regActiveComputerName, regComputerName, regHostname
    Dim ActiveComputerName, ComputerName, Hostname
    'When you use a variable name and then an equal sign (=)
    'you're saying the variable contains the information on the right.
    'The registry keys are quite long, so make them easier to read on
    'a single screen by splitting the line in two.

    regActiveComputerName = "HKLM\SYSTEM\CurrentControlSet" & _
        "\Control\ComputerName\ActiveComputerName\ComputerName"
    regComputerName = "HKLM\SYSTEM\CurrentControlSet\Control" & _
        "\ComputerName\ComputerName\ComputerName"
    regHostname = "HKLM\SYSTEM\CurrentControlSet\Services" & _
        "\Tcpip\Parameters\Hostname"


    Set bjShell = CreateObject("WScript.Shell")
    ActiveComputerName = objShell.RegRead(regActiveComputerName)
    ComputerName = objShell.RegRead(regComputerName)
    Hostname = objShell.RegRead(regHostname)

    'To make dialog boxes you can use WScript.Echo
    'and then tell it what you want it to say.

    WScript.Echo activecomputername & " is active computer name"
    WScript.Echo ComputerName & " is computer name"
    WScript.Echo Hostname & " is host name"

    例3 registry keys Information.VBS

    Option Explicit
    On Error Resume Next
    Dim objShell
    Dim regLogonUserName, regServiceInformation, regGPServer
    Dim regLogonServer, regDNSdomain
    Dim LogonUserName, ServiceInformation, GPServer
    Dim LogonServer, DNSdomain
    regLogonUserName = "HKEY_CURRENT_USER\Software\Microsoft\" & _
        "Windows\CurrentVersion\Explorer\Logon User Name"
    regServiceInformation = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServiceCurrent"
    regGPServer = "HKEY_CURRENT_USER\Software\Microsoft\Windows\" & _
        "CurrentVersion\Group Policy\History\DCName"
    regLogonServer = "HKEY_CURRENT_USER\Volatile Environment\" & _
        "LOGONSERVER"
    regDNSdomain = "HKEY_CURRENT_USER\Volatile Environment\" & _
        "USERDNSDOMAIN"
    Set bjShell = CreateObject("WScript.Shell")
    LogonUserName = objShell.RegRead(regLogonUserName)
    ServiceInformation = objShell.RegRead(regServiceInformation)
    GPServer = objShell.RegRead(regGPServer)
    LogonServer = objShell.RegRead(regLogonServer)
    DNSdomain = objShell.RegRead(regDNSdomain)
    WScript.Echo LogonUserName & " is currently Logged on"
    WScript.Echo ServiceInformation & " is the current service current"
    WScript.Echo GPServer & " is the current Group Policy Server"
    WScript.Echo LogonServer & " is the current logon server"
    WScript.Echo DNSdomain & " is the current DNS domain"

     

    例4 Crash Recovery Information.VBS

    Option Explicit
    On Error Resume Next
    Dim objShell
    Dim regLogonUserName, regServiceInformation, regGPServer
    Dim regLogonServer, regDNSdomain
    Dim LogonUserName, ServiceInformation, GPServer
    Dim LogonServer, DNSdomain
    regLogonUserName = "HKEY_CURRENT_USER\Software\Microsoft\" & _
        "Windows\CurrentVersion\Explorer\Logon User Name"
    regServiceInformation = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServiceCurrent"
    regGPServer = "HKEY_CURRENT_USER\Software\Microsoft\Windows\" & _
        "CurrentVersion\Group Policy\History\DCName"
    regLogonServer = "HKEY_CURRENT_USER\Volatile Environment\" & _
        "LOGONSERVER"
    regDNSdomain = "HKEY_CURRENT_USER\Volatile Environment\" & _
        "USERDNSDOMAIN"
    Set bjShell = CreateObject("WScript.Shell")
    LogonUserName = objShell.RegRead(regLogonUserName)
    ServiceInformation = objShell.RegRead(regServiceInformation)
    GPServer = objShell.RegRead(regGPServer)
    LogonServer = objShell.RegRead(regLogonServer)
    DNSdomain = objShell.RegRead(regDNSdomain)
    WScript.Echo LogonUserName & " is currently Logged on"
    WScript.Echo ServiceInformation & " is the current service current"
    WScript.Echo GPServer & " is the current Group Policy Server"
    WScript.Echo LogonServer & " is the current logon server"
    WScript.Echo DNSdomain & " is the current DNS domain"

     

     

     

    From
    Microsoft® VBScript. Step by Step
    By Ed Wilson

  • VBS例子

    2010-03-22 00:20:22

    例1

    定义一个数组, 包含5个元素, 都是随机整数(随便输入), 要求把他们按照从大到小的顺序排列起来

    Option Explicit
    Dim a(4)
    Dim i
    Dim j
    Dim temp

    For  i =0  to 4
    a(i) = inputbox ("请输入第" &(i+1) &"个元素 ")
    Next

    For i = 0  to 4
     For j = (i+1) to 4
      If  a(i) < a(j) Then
       temp = a(i)
       a(i) = a(j)
       a(j) = temp
      End If
     Next
    Next
    msgbox (a(0)&" "&a(1)&" "&a(2)&" "&a(3)&" "&a(4))

  • VBScript

    2010-03-21 23:25:44

    VBScriptVisual Basic Script的简称,有时也被缩写为VBS。VBScript是微软开发的一种脚本语言,可以看作是VB语言的简化版,与VBA的关系也非常密切。它具有原语言容易学习的特性。目前这种语言广泛应用于网页和ASP程序制作,同时还可以直接作为一个可执行程序。用于调试简单的VB语句非常方便。

    目录

    使用范围

    由于VBScript可以通过Windows脚本宿主调用COM,因而可以使用Windows操作系统中可以被使用的程序,比如它可以使用Microsoft Office的库,尤其是使用Microsoft AccessMicrosoft SQL Server的程序库,当然它也可以使用其它程序和操作系统本身的库。在实践中VBScript一般被用在以下三个方面:

    Windows操作系统

    VBScript可以被用来自动地完成重复性的Windows操作系统任务。在Windows操作系统中,VBScript可以在Windows Script. Host的范围内运行。Windows操作系统可以自动辨认和执行*.VBS和*.WSF两种文档格式,此外Internet Explorer可以执行HTA和CHM文档格式。VBS和WSF文档完全是文字式的,它们只能通过少数几种对话窗口与用户通讯。HTA和CHM文档使用HTML格式,它们的程序码可以象HTML一样被编辑和检查。在WSF、HTA和CHM文档中VBScript和JavaScript的程序码可以任意混合。HTA文档实际上是加有VBS、JavaScript成分的HTML文档。CHM文档是一种在线帮助,用户可以使用专门的编辑程序将HTML程序编辑为CHM。

    网页浏览器(客户端的VBS)

    网页中的VBS可以用来控制客户端的网页浏览器(以浏览器执行VBS程序)。VBS与JavaScript在这一方面是竞争者,它们可以用来实现动态HTML,甚至可以将整个程序结合到网页中来。

    至今为止VBS在客户方面未能占优势,因为它只获得Microsoft Internet Explorer的支持(Mozilla Suite可以透过安装一个来支持VBS)。而JavaScript则受到所有网页浏览器的支持。在Internet Explorer中VBS和JavaScript使用同样的权限,它们只能有限地使用Windows操作系统中的对象。

    网页服务器(服务器方面的VBS)

    在网页服务器方面VBS是微软的Active Server Pages的一部分,它与JavaServer PagesPHP是竞争对手。在这里VBS的程序码直接嵌入到HTML页内,这样的网页以ASP结尾。网页服务器Internet信息服务执行ASP页内的程序部分并将其结果转化为HTML传递给网页浏览器供用户使用。这样服务器可以进行数据库闻讯并将其结果放到HTML网页中。

    语言

    VBScript主要的优点有:

    • 由于VBScript由操作系统,而不是由网页浏览器解释,它的文档比较小。
    • 易学。
    • 在所有2000 / 98SE以后的Windows版本都可直接使用。
    • 可以使用其它程序和可使用的对象(尤其Microsoft Office)。

    缺点有:

    • 现在VBS无法作为电子邮件的附件了。Microsoft Outlook拒绝接受VBS为附件,收信人无法直接使用VBS附件。
    • VBS的各种编辑器不受欢迎。
    • 操作系统没有任何特别的保护设施。VBS程序与其它JS、EXE、BAT或CMD程序一样对待。操作系统没有监察恶意功能的能力。

    和VB的对比

    不能为变量定义类型

    在VB中,为变量定义类型使用Dim变量名As类型

    但是在VBScript中这样写是错误的。只能使用Dim变量名,解释器会自动根据赋值的类型定义变量类型。

    不能使用条件编译

    在VB中,可以使用#If…Then、#ElseIf…Then、#Else、#End If、#Const… = …等语句定义编译时使用的语句

    而由于VBScript不需要编译即可直接执行,所以并不需要条件编译语句。

    安全性

    微软决定Outlook和Outlook Express中的HTML邮件可以使用VBScript后出现了许多利用Windows Script. Host和ActiveX的功能的电脑病毒。这些病毒之所以能够传播开来也是因为一开始这些系统功能完全未受保护。虽然VBScript和JavaScript使用同样的使用操作系统的功能的安全措施,今天呼唤这些功能被看作不符合标准。

    一般很难保护VBScript的程序码不被用户看到。

312/2<12
Open Toolbar