发布新日志

  • File Attributes

    2010-03-31 00:11:03

    Table 6-3. File attributes and bitmask values

    Attribute

    Bitmask value

    Meaning

    Normal

    0

    No attributes set

    Read-only

    1

    File can be read but not changed

    Hidden

    2

    File cannot be seen in default view of Microsoft Windows Explorer

    System

    4

    File is used by the operating system (OS)

    Archive

    32

    File changed since last backup

    Alias

    64

    File is a shortcut to another file

    Compressed

    2048

    File has been compressed

     

     

    FileAttributes.vbs

    Option Explicit
    On Error Resume Next
    Dim objFSO
    Dim objFile
    Dim Target
    
    Target = "C:\fso\test.txt"
    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjFile = objFSO.GetFile(Target)
    
    WScript.Echo "The file is: " & target
    WScript.Echo "bitmap number is: " & objFile.Attributes & _
       " " & funAttrib(objFile.attributes)
    
    
    Function funAttrib(intMask)
    Dim strAttrib
    If IntMask = 0 Then strAttrib = "No attributes"
    If intMask And 1 Then strAttrib = strAttrib & "Read Only, "
    If intMask And 2 Then strAttrib = strAttrib & "Hidden, "
    If intMask And 4 Then strAttrib = strAttrib & "System, "
    If intMask And 8 Then strAttrib = strAttrib & "Volume, "
    If intMask And 16 Then strAttrib = strAttrib & "Directory, "
    If intMask And 32 Then strAttrib = strAttrib & "Archive, "
    If intMask And 64 Then strAttrib = strAttrib & "Alias, "
    If intMask And 2048 Then strAttrib = strAttrib & "Compressed, "
    funAttrib = strAttrib
    End Function
  • File Properties

    2010-03-31 00:09:39

    Additional file object properties can be retrieved in the same manner. All are listed in Table 6-2.

    Table 6-2. File properties

    Property

    Use

    Attributes

    Bitmask representation of the file attributes such as read-only and hidden.

    DateCreated

    Date the file was created.

    DateLastAccessed

    Date the file was last accessed.

    DateLastModified

    Date the file was last modified.

    Drive

    The drive letter representing where the file is stored, followed by a colon (for example, C:).

    Name

    The name of the file, not including the path information (for example, ListFiles.vbs). The name does include the extension.

    ParentFolder

    The folder in which the file is located (not including subfolders). For example, the parent folder of C:\windows\system32\logfile.txt is Windows.

    Path

    The full path of the file (for example, C:\windows\system32\logfile.txt).

    ShortName

    8.3 (MS-DOS format) version of the file name. For example, MyLongFileName.txt might become MyLong~1.txt.

    ShortPath

    8.3 (MS-DOS style) version of the path. For example, C:\MyLongPath\MyLongFileName.txt might become C:\MyLong~1\MyLong~1.txt.

    Size

    The size of the file in bytes.

    Type

    The type of file as recorded in the registry. For example, a .doc file is listed as a Microsoft Word document.

  • File It Under Files

    2010-03-31 00:04:32

    In your first file system script, ListFiles.vbs, connect to FileSystemObject, attach it to a folder defined by the variable FolderPath, and then use the Files command to enable the For Each loop to echo out each file in the folder. This is just the beginning of what can be done with this script.

     

    Table 6-1. Variables used in ListFiles.vbs

    Variable name

    Use

    FolderPath

    Defines the folder to be enumerated in the script

    objFSO

    Creates FileSystemObject

    objFolder

    Holds the connection to the folder whose path is stored in the FolderPath variable. The connection is returned by the GetFolder method of FileSystemObject

    colFiles

    Holds the collection of files returned by using the Files method

    objFile

    Holds individual files as the script. iterates through the collection of files by using the For Each construction

     

     

    ListFiles.vbs

    Option Explicit
    On Error Resume Next
    Dim FolderPath        'path to the folder to be searched for files
    Dim objFSO            'the FileSystemObject
    Dim objFolder         'the folder object
    Dim colFiles          'collection of files from files method
    Dim objFile           'individual file object
    
    FolderPath = "c:\fso"
    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjFolder = objFSO.GetFolder(FolderPath)
    Set colFiles = objFolder.Files
    
    For Each objFile in colFiles
      WScript.Echo objFile.Name, objFile.Size & " bytes"
      WScript.Echo VbTab & "created: " & objFile.DateCreated
      WScript.Echo VbTab & "modified: " & objFile.DateLastModified
    Next
     
     
     
    one function to offer the objpath
    Sub subGetFolder
    Dim objShell, objFolder, objFolderItem, objPath
    Const windowHandle = 0
    Const folderOnly = 0
    const folderAndFiles = &H4000&
    
    Set bjShell = CreateObject("Shell.Application")
    Set bjFOlder = objShell.BrowseForFolder(windowHandle, _
       "Select a folder:", folderOnly)
    Set bjFolderItem = objFolder.Self
    bjPath = objFolderItem.Path
    End Sub
  • Creating a Dictionary

    2010-03-29 19:58:37

    Chapter 5 Quick Reference

    To

    Do This

    Use a string to populate an array

    Use the Split function to turn the string into an array

    Resize a dynamic array

    Use the ReDim command

    Resize a dynamic array and keep the existing data in it

    Use the ReDim command with the Preserve keyword

    Change the way string values are compared in a Dictionary object

    Change the Compare Mode property of the dictionary object

    Create a Dictionary object

    Use the createObject command and specify the scripting.dictionary program ID

    Determine how many items are in the dictionary

    Use the Count property

    Determine if an item exists in the dictionary prior to adding it

    Use the Exists method

    Obtain a collection of keys from the dictionary

    Use the Keys method


     

    YourNameDictionary.vbs


    Option Explicit
    Dim objDictionary   'the dictionary object
    Dim objFSO          'the FileSystemObject object
    Dim objFolder       'created by GetFolder method
    Dim colFiles        'collection of files from Files method
    Dim objFile         'individual file
    Dim aryKeys         'array of keys
    Dim strKey          'individual key from array of keys
    Dim strFolder       'the folder to obtain listing of files

    strFolder = "c:\windows"
    Set bjDictionary = CreateObject("Scripting.Dictionary") 'connect dictionary
    Set bjFSO = CreateObject("Scripting.FileSystemObject") ' connect filesystemobject
    Set bjFolder = objFSO.GetFolder(strFolder) 'get path "c:\windows" all folders
    Set colFiles = objFolder.Files
    For Each objFile In colFiles  'using for each next to throgh all items with the files
    objDictionary.Add objFile.Name, objFile.Size
    Next
    aryKeys = objDictionary.Keys
    For Each strKey In aryKeys
    WScript.Echo "The file: " & strKey & " is: " & _
    objDictionary.Item(strKey) & " bytes"
    Next
    WScript.Echo "Directory listing of " & strFolder
    WScript.Echo "***there are " & objDictionary.count & " files"

  • Parsing Passed Text into an Array

    2010-03-28 22:12:25

    In our script, SearchTXT.vbs, you create a dynamic array and set its initial size to zero. You next make a connection to the file system object and open the Setuplog.txt file, located in the Windows directory (this path may be edited if required), for reading. Once the Setuplog.txt file is opened for reading, you define a search string of "Error" and use the InStr command to look through each line. If the string "Error" is found on the line being examined, the line with the error is added to the array. You then increment the next element in the array in case you find another line with the string "Error" in it. After you go through the entire text file, you use a For...Next loop and echo out each element of the array. The script. concludes with a friendly "all done" message.
     
     Table 5-1. Variables declared in SearchTXT.vbs

    Variable

    Use

    arrTxtArray()

    Declares a dynamic array

    myFile

    Holds the file name of the file to open up

    SearchString

    Holds the string to search for

    objTextFile

    Holds the connection to the text file

    strNextLine

    Holds the next line in the text stream

    intSize

    Holds the initial size of the array

    objFSO

    Holds the connection to the file system object

    i

    Used to increment intSize counter

    SearchTXT.vbs

    Option Explicit
    On Error Resume Next
    Dim arrTxtArray()
    Dim myFile
    Dim SearchString
    Dim objTextFile
    Dim strNextLine
    Dim intSize
    Dim objFSO
    Dim i
    intSize = 0
    myFile = "c:\windows\setuplog.txt" <'>Modify as required
    SearchString = "Error"
    Const ForReading = 1
    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjTextFile = objFSO.OpenTextFile _
      (myFile, ForReading)
    Do until objTextFile.AtEndOfStream
      strNextLine = objTextFile.ReadLine
      if InStr (strNextLine, SearchString)then
       ReDim Preserve arrTxtArray(intSize)
       arrTxtArray(intSize) = strNextLine
       intSize = intSize + 1
      End If
    Loop
    objTextFile.close
    For i = LBound(arrTxtArray) To UBound(arrTxtArray)
       WScript.Echo arrTxtArray(i)
    Next
    WScript.Echo("all done")
     
     
     
    ParseAppLog.vbs
    Table 5-2. Variables declared in ParseAppLog.vbs

    Variable

    Use

    arrTxtArray()

    Declares a dynamic array

    appLog

    Holds the file name of the file to open

    SearchString

    Holds the string to search for

    objTextFile

    Holds the connection to the text file

    strNextLine

    Holds the next line in the text stream

    intSize

    Holds the initial size of the array

    objFSO

    Holds the connection to the file system object

    i

    Used to increment the intSize counter

    ErrorString

    Holds the second search string used

    newArray

    New array created to sort the output

    Option Explicit
    On Error Resume Next
    Dim arrTxtArray()
    Dim appLog
    Dim SearchString
    Dim objTextFile
    Dim strNextLine
    Dim intSize
    Dim objFSO
    Dim i
    Dim ErrorString
    Dim newArray
    intSize = 0
    appLog = "applog.csv" <'>Ensure in path
    SearchString = ","
    ErrorString = "1004"
    Const ForReading = 1
    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjTextFile = objFSO.OpenTextFile _
      (appLog, ForReading)
    Do until objTextFile.AtEndOfStream
      strNextLine = objTextFile.ReadLine
      if InStr (strNextLine, SearchString)Then
       If InStr (strNextLine, ErrorString) then
             ReDim Preserve arrTxtArray(intSize)
             arrTxtArray(intSize) = strNextLine
             intSize = intSize + 1
         End If
      End If
    Loop
       objTextFile.close
    For i = LBound(arrTxtArray) To UBound(arrTxtArray)
       If InStr (arrTxtArray(i), ",") Then
       newArray = Split (arrTxtArray(i), ",")
             WScript.Echo "Date: " & newArray(0)
             WScript.Echo "Time: " & newArray(1)
             WScript.Echo "Source: " & newArray(2)& " "& newArray(3)
             WScript.Echo "Server: " & newArray(7)
             WScript.Echo "Message1: " & newArray(8)
             WScript.Echo "Message2: " & newArray(9)
             WScript.Echo "Message3: " & newArray(10)
             WScript.Echo " "
       End If
    Next
    WScript.Echo("all done")
     
     
     
     

    Quick Check

    Q.

    What is the advantage of using a dynamic array?

    A.

    You can expand a dynamic array when a new element is needed. This saves memory and is more efficient.

    Q.

    How is ReDim Preserve used?

    A.

    ReDim Preserve is used to resize a dynamic array while ensuring that the data contained in the array is not lost.

    Q.

    What is the simplest way to break up a CSV data stream to populate an array?

    A.

    You need to use the Split command and look for commas.

    Q.

    What is the InStr command used for?

    A.

    The InStr command is used to look for character combinations in a stream of text.

    Q.

    What construct can be used to hold data records that are separated by commas?

    A.

    A multidimensional array can be used to hold this type of data.

  • Two-Dimensional Arrays

    2010-03-28 00:42:02

    To create a two-dimensional array, include both dimensions when you declare the variable used for the array, as illustrated here:

    Dim a (3,3)
    Table 4-2. Two-dimensional array

    0,0

    0,1

    0,2

    0,3

    1,0

    1,1

    1,2

    1,3

    2,0

    2,1

    2,2

    2,3

    3,0

    3,1

    3,2

    3,3

     

    WorkWith2DArray.vbs

    Option Explicit
    Dim i
    Dim j
    Dim numLoop
    Dim a (3,3)
    numLoop = 0
    For i = 0 To 3
      For j = 0 To 3
        numLoop = numLoop+1
        WScript.Echo "i = " & i & " j = " & j
        a(i, j) = "loop " & numLoop
        WScript.Echo "Value stored In a(i,j) is: " & a(i,j)
      Next
    Next
    execute result
    C:\>cscript. example.vbs
    Microsoft (R) Windows Script. Host Version 5.6
    Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
    i = 0 j = 0
    Value stored In a(i,j) is: loop 1
    i = 0 j = 1
    Value stored In a(i,j) is: loop 2
    i = 0 j = 2
    Value stored In a(i,j) is: loop 3
    i = 0 j = 3
    Value stored In a(i,j) is: loop 4
    i = 1 j = 0
    Value stored In a(i,j) is: loop 5
    i = 1 j = 1
    Value stored In a(i,j) is: loop 6
    i = 1 j = 2
    Value stored In a(i,j) is: loop 7
    i = 1 j = 3
    Value stored In a(i,j) is: loop 8
    i = 2 j = 0
    Value stored In a(i,j) is: loop 9
    i = 2 j = 1
    Value stored In a(i,j) is: loop 10
    i = 2 j = 2
    Value stored In a(i,j) is: loop 11
    i = 2 j = 3
    Value stored In a(i,j) is: loop 12
    i = 3 j = 0
    Value stored In a(i,j) is: loop 13
    i = 3 j = 1
    Value stored In a(i,j) is: loop 14
    i = 3 j = 2
    Value stored In a(i,j) is: loop 15
    i = 3 j = 3
    Value stored In a(i,j) Is: Loop 16
  • How to read a text file

    2010-03-28 00:15:47

    Quick Check

     

    Q.

    How can the population of an array be automated?

    A.

    You can automate the population of an array by using the For...Next command.

    Q.

    If you do not know in advance how many elements are going to be in the array, how can you automate the population of an array?

    A.

    You can automate the population of an array with an unknown number of elements by using the For...Next command in conjunction with UBound.

    ArrayReadTxtFile.vbs

    through the split function to create a single dimension array and When you use the suffixes (0) and (i) in the WScript.Echo statement, VBScript. knows you want to refer to elements in the array

    Option Explicit
    Dim objFSO
    Dim objTextFile
    Dim strNextLine
    Dim arrServiceList
    Dim i
    Const ForReading = 1
    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjTextFile = objFSO.OpenTextFile("c:\Test.txt",ForReading)

    Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.ReadLine
    arrServiceList = Split(strNextLine,",")
    WScript.Echo arrServiceList(0)
    Loop

    For i = 1 To UBound(arrServiceList)
    WScript.Echo arrServiceList(i-1)
    Next

    WScript.Echo ("all done")

  • Working with Arrays--two examples

    2010-03-28 00:10:40

    BasicArrayForEachNext.vbs

    Option Explicit
    On Error Resume Next
    Dim myTab 'Holds custom tab of two places
    Dim aryComputer 'Holds array of computer names
    Dim computer    'Individual computer from the array
    Dim I           'Simple counter variable. Used to retrieve by
                    'Element number in the array.
    myTab = Space(2) 'two blankspaces
    i = 0           'The first element in an array is 0.
    aryComputer = array("s1","s2","s3")

    WScript.Echo "Retrieve via for each next"
    For Each computer In aryComputer
             WScript.Echo myTab & "computer # " & i & _
             " is " & computer
       i = i+1
    Next

     

     

    BasicArrayForNext.vbs

    Option Explicit
    On Error Resume Next
    Dim myTab 'Holds custom tab of two places
    Dim aryComputer 'Holds array of computer names
    Dim computer    'Individual computer from the array
    Dim i           'Simple counter variable. Used to retrieve by
                    'Element number in the array.
    myTab = Space(2)
    i = 0           'The first element in an array is 0.
    aryComputer = array("s1","s2","s3")
    
    
    WScript.Echo "Retrieve via for next"
    i = 0
    For i = 0 To UBound(aryComputer)
       WScript.Echo myTab & "computer # " & i & _
             " is " & aryComputer(i)
    Next
     
     
    from
    Microsoft@ VBScript. Step by Step
    By Ed Wilson
     
     
     
  • Working with Arrays--two examples

    2010-03-28 00:10:40

    BasicArrayForEachNext.vbs

    Option Explicit
    On Error Resume Next
    Dim myTab 'Holds custom tab of two places
    Dim aryComputer 'Holds array of computer names
    Dim computer    'Individual computer from the array
    Dim I           'Simple counter variable. Used to retrieve by
                    'Element number in the array.
    myTab = Space(2) 'two blankspaces
    i = 0           'The first element in an array is 0.
    aryComputer = array("s1","s2","s3")

    WScript.Echo "Retrieve via for each next"
    For Each computer In aryComputer
             WScript.Echo myTab & "computer # " & i & _
             " is " & computer
       i = i+1
    Next

     

     

    BasicArrayForNext.vbs

    Option Explicit
    On Error Resume Next
    Dim myTab 'Holds custom tab of two places
    Dim aryComputer 'Holds array of computer names
    Dim computer    'Individual computer from the array
    Dim i           'Simple counter variable. Used to retrieve by
                    'Element number in the array.
    myTab = Space(2)
    i = 0           'The first element in an array is 0.
    aryComputer = array("s1","s2","s3")
    
    
    WScript.Echo "Retrieve via for next"
    i = 0
    For i = 0 To UBound(aryComputer)
       WScript.Echo myTab & "computer # " & i & _
             " is " & aryComputer(i)
    Next
     
     
    from
    Microsoft@ VBScript. Step by Step
    By Ed Wilson
     
     
     
  • Named Arguments

    2010-03-26 22:36:28

    Q.

    What is one reason for using named arguments?

    A.

    With named arguments, when you have multiple command-line arguments, you don't need to remember in which order to type the arguments.

    Q.

    How do you run a script. with named arguments?

    A.

    To run a script. with named arguments, you use a forward slash and then enter the name of the argument. You follow this with a colon and the value you want to use.

     

    YourNameCheckNamedArgCS.vbs

    Option Explicit
    'On Error Resume Next
    Dim computerName
    Dim serviceName
    Dim wmiRoot
    Dim wmiQuery
    Dim objWMIService
    Dim colServices
    Dim oservice
    Dim colNamedArguments
    Set colNamedArguments = WScript.Arguments.Named
    computerName = colNamedArguments("computer")
    serviceName = colNamedArguments("service")
    subCheckArgs
    wmiRoot = "winmgmts:\\" & computerName & "\root\cimv2"
    wmiQuery = "Select state from Win32_Service" & " where name = " & "'" & serviceName & "'"

    Set bjWMIService = GetObject(wmiRoot)
    Set colServices = objWMIService.ExecQuery(wmiQuery)
    For Each oservice In colServices
       WScript.Echo serviceName & " Is: " & oservice.state & " on: " & computerName
    Next


    Sub subCheckArgs
    If colNamedArguments.Count < 2 Then
    If colNamedArguments.exists("computer") Then
    serviceName = "spooler"
    WScript.Echo "using default service: spooler"
    Else If colNamedArguments.Exists("Service") Then
    computerName = "localHost"
    WScript.Echo "using default computer: localhost"
    Else
    WScript.Echo "you must supply two arguments" _
    & " to this script." & VbCrLf & "Try this: " _
    & "Cscript. checkNamedArgCS.vbs /computer:" _
    & "localhost /service:spooler"      
    WScript.Quit
    End If
    End If
    End If
    End Sub

     

    From

    Microsoft@ VBScript. Step by Step
    By Ed Wilson

     

     

     

  • Using Multiple Arguments

    2010-03-26 21:15:22

    Table 4-1. Variables used in ArgComputerService.vbs

    Variable Name

    Use

    computerName

    Holds the first command-line argument

    serviceName

    Holds the second command-line argument

    wmiRoot

    Holds the namespace of WMI

    wmiQuery

    Holds the query issued to WMI

    objWMIService

    Holds the connection into WMI

    colServices

    Holds the result of the WMI query

    oservice

    Holds each service in colServices as you walk through the collection

    CMD command prompt and use the following command:

    Cscript. argComputerService.vbs localhost lanmanserver
     
    the result:lanmanserver Is: Running on: localhost
     
     

    ArgComputerService.vbs

    Option Explicit
    On Error Resume Next
    Dim computerName
    Dim serviceName
    Dim wmiRoot
    Dim wmiQuery
    Dim objWMIService
    Dim colServices
    Dim oservice
    
    computerName = WScript.Arguments(0)
    serviceName = WScript.Arguments(1)
    wmiRoot = "winmgmts:\\" & computerName & "\root\cimv2"
    Set bjWMIService = GetObject(wmiRoot)
    wmiQuery = "Select state from Win32_Service" &_
       " where name = " & "'" & serviceName & "'"
    Set colServices = objWMIService.ExecQuery _
      (wmiQuery)
    For Each oservice In colServices
       WScript.Echo (serviceName) & " Is: "&_
       oservice.state & (" on: ") & computerName
    Next


     

     

    From

    Microsoft@ VBScript. Step by Step
    By Ed Wilson

     

     

  • Creating a Useful Error Message--Arguments

    2010-03-26 20:59:17

    Command-Line Arguments

    Command-line arguments provide you with the ability to modify the execution of a script. prior to running it.

     

    CheckArgsPingMultipleComputers.vbs

    Option Explicit
    On Error Resume Next
    Dim strComputer
    Dim aMachines,machine
    Dim objPing,objStatus


    strComputer = WScript.Arguments.Item(0)
    aMachines = Split(strComputer, ",")
    For Each machine In aMachines
    Set bjPing = GetObject("winmgmts:{impersonationLevel = impersonate}"). _
    ExecQuery("select * from Win32_PingStatus where address = '" _
    & machine & "'")
    For Each objStatus In objPing
    If IsNull(objStatus.StatusCode) Or objStatus.StatusCode<>0 Then
    WScript.Echo ("mahine" & machine & "is not reachable")
    Else
    WScript.Echo ("reply from" & machine)
    End If
    Next
    Next
    Sub subCheckArgs
    If WScript.Arguments.Count = 0 Then
    WScript.Echo "You must enter a computer to ping" & VbCrLf & _
    "Try this: Cscript. CheckArgsPingMultipeComputers.vbs" & "127.0.0.1;localhost"
    WScript.Quit
    End If
    End Sub

     

    From

    Microsoft@ VBScript. Step by Step
    By Ed Wilson

     

     

     

  • Two Examples

    2010-03-26 01:19:32

    YourNameComputerRoles Solution.vbs

    Option Explicit
    'On Error Resume Next
    Dim strComputer
    Dim wmiRoot
    Dim wmiQuery
    Dim colComputers
    Dim objComputer
    Dim objWMIService
    Dim strComputerRole,strComputerName,strDomainName,strUserName
    strComputer = "."
    wmiRoot = "winmgmts:\\" & strComputer & "\root\cimv2"
    wmiQuery = "Select * from Win32_ComputerSystem"

    Set bjWMIService = GetObject(wmiRoot)
    Set colComputers = objWMIService.ExecQuery(wmiQuery)
    For Each objComputer In colComputers
      strComputerRole = funComputerRole(objComputer.DomainRole)
      strComputerName = objComputer.Name
      strDomainName = objComputer.Domain
      strUserName = objComputer.UserName
      WScript.Echo  strComputerRole & VbCrLf & strComputerName _
      & VbCrLf & strDomainName & VbCrLf & strUserName
      Next
    WScript.Echo("all done")
    Function funComputerRole(intIN)
     Select Case intIN
      Case 0
        funComputerRole = "Standalone Workstation"
      Case 1
        funComputerRole = "Member Workstation"
      Case 2
        funComputerRole = "Standalone Server"
      Case 3
        funComputerRole = "Member Server"
      Case 4
        funComputerRole = "Backup Domain Controller"
      Case 5
        funComputerRole = "Primary Domain Controller"
      Case Else
      funComputerRole = "Look this one up in SDK"
     End Select
    End Function

     

    YourNameEnableDHCPSolution.vbs

    Option Explicit
    'On Error Resume Next
    Dim strComputer
    Dim wmiRoot
    Dim wmiQuery
    Dim objWMIService
    Dim colNetAdapters,objNetAdapter,DHCPEnabled
    strComputer = "."
    wmiRoot = "winmgmts:\\" & strComputer & "\root\cimv2"
    wmiQuery = "Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"

    Set bjWMIService = GetObject(wmiRoot)
    Set colNetAdapters = objWMIService.ExecQuery (wmiQuery)
    For Each objNetAdapter In colNetAdapters
    DHCPEnabled = objNetAdapter.EnableDHCP()
    If DHCPEnabled = 0 Then
      WScript.Echo "DHCP has been enabled."
      Else
      WScript.Echo "DHCP could not be enabled."
    End If
    Next

     

  • WMI

    2010-03-26 00:07:22

    简介

       WMI是Windows 2K/XP管理系统的核心;对于其他的Win32操作系统,WMI是一个有用的插件。WMI以CIMOM为基础,CIMOM即公共信息模型对象管理器(Common Information Model Object Manager),


       是一个描述操作系统构成单元的对象数据库,为MMC和脚本程序提供了一个访问操作系统构成单元的公共接口。有了WMI,工具软件和脚本程序访问操作系统的不同部分时不需要使用不同的API;相反,操作系统的不同部分都可以插入WMI,如图一所示(该图来自MSDN),工具软件和WMI可以方便地读写WMI。

      Windows 2K/XP和Windows 98 都支持WMI;如果为NT 4.0和Windows 95加上了 Service Pack 4或更高版本,NT 4.0和Win95也支持WMI。因此,用WMI进行远程管理时,并非一定要用Windows 2K/XP(当然,如果WMI脚本在一台没有性能监视器的Win9x机器上运行,就不能在远程Win9x系统上查询Windows 2K/XP的性能监视器。

      如前所述,WMI允许通过一个公共的接口访问多种操作系统构成单元,因此不必分别对待各种底层接口或所谓的“提供者”。利用WMI可以高效地管理远程和本地的计算机;与此相对,并非所有的Windows 2K/XP命令行工具都支持远程运行。

      WMI是WBEM模型的一种实现。WBEM即Web-Based Enterprise Management,或基于Web的企业管理,WBEM由DMTF(Distributed Management Task Force,分布式管理任务组)在许多厂商的帮助下创立,包括Compaq、Sun、Microsoft等。WBEM的目标是,为管理企业环境开发一个标准的接口集。WBEM模型最关键的部分是它的数据模型(或描述和定义对象的方式)、编码规范(Encoding Specification),以及在客户端和服务器端之间传输数据的模式。

      WBEM的数据模型是CIM(Common Information Model,公共信息模型)。CIM是一个用来命名计算机的物理和逻辑单元的标准的命名系统(或称为命名模式),例如硬盘的逻辑分区、正在运行的应用的一个实例,或者一条电缆。

      CIM是一个面向对象的模型,使用一组面向对象的术语进行描述。CIM包含类(Class),类是被管理单元的模板。类的实例称为对象(Object),对象代表着底层系统的一个具体单元。名称空间(Namespace)是一个类的集合,每个名称空间面向一个特定的管理领域。类包含属性(Property)和方法(Method)。

      CIM分三层。第一层是核心模型(Core Model),这一层包含的类定义对于所有管理领域来说都是共同的。第二层是公共模型(Common Model),这一层包含的类定义对于特定的管理领域来说是公共的,但与具体的操作系统和系统设计无关。第三层是扩展模型(Extension model),这一层包含的类定义与特定的操作系统或技术有关。

      WMI是Microsoft扩展CIM 2.0得到的面向Win32系统的扩展模型。引用WMI类和属性的形式是“扩展前缀_类名称.属性名称”,例如Win32_ComputerSystem.Name,其中Win32是CIM模式cimv2名称空间内WMI扩展类的前缀,ComputerSystem是类,Name是属性。

      编写WMI脚本的很大一部分工作涉及到读取和设置属性值。当前,WMI提供的方法还很有限,但随着时间的推移,相信WMI和CIM提供的方法都会越来越丰富。

     

    操作方法

       利用WMI软件开发包(SDK)可以方便地查看可用的CIM和Win32类。WMI SDK可以从MSDN下载。

      WMI SDK要求操作系统必须是Windows 2K/XP或者NT 4.0 SP4或更高版本;尽管Win9x系统上可以安装WMI支持软件,但SDK不能在Win9x上运行。另外,为支持SDK的ActiveX控件,SDK还要求有IE 5.0或更高版本。SDK对机器性能的最低要求是:Pentium处理器,32 Mb的RAM,40 Mb的磁盘空间,以及至少要有800 x 600、256色的显示设备。对于运行Windows 2K/XP的机器来说,这些要求应该不会成为问题。CIMOM默认以服务的形式运行,但如果机器没有网卡,CIMOM不能作为服务运行,不过此时可以作为一个应用运行,只需执行winmgmt.exe即可。winmgmt.exe在\%systemroot%\system32\wbem的WMI主目录下。

      SDK必须由管理员组的成员安装。安装过程很简单,执行WMISdk.exe启动向导,指定安装的目标目录(默认是\program files\wmi)。选择要安装的可选组件(默认安装除了SNMP支持以外的所有组件),最后点击Finish。安装SDK不需要重新启动。安装完成后,“开始/程序”菜单上会增加一个WMI SDK组。

      点击WMI SDK程序组的WMI CIM Studio。CIM Studio提示连接名称空间,并显示默认连接的名称空间是root\cimv2,确认即可。如果你用Administrator身份登录Windows,再次点击确定以当前身份登录;如果你用其他的身份登录Windows,请改用Administrator登录。

      现在,假设我们要在当前的机器上查找一个对象:C:驱动器。我们不知道C:驱动器在CIM或WMI中的具体名称,浏览CIM Studio列出的数百个类又太麻烦,怎么办呢?可以使用Find按钮(左边上方的望远镜,参见图三)。图二显示了点击Find按钮后显示的Search for Class对话框,在这里输入我们猜想C:驱动器的类名称中应当包含的单词,然后点击Go!按钮。由于我们正在寻找一个命名的磁盘分区,而且我们知道Windows把这种分区叫做logical disk或logical drive,因此这里的搜索关键词可以是logical。当然,搜索关键词也可以是disk,但这时会有大量的搜索结果出现。

      图二显示了搜索关键词logical得到的结果。选择Win32_LogicalDisk并点击OK,图三的窗口出现(为什么不选择CIM_LogicalDisk?前面已经提到,WMI管理的所有对象都带有Win32前缀。如果选择CIM_LogicalDisk然后要求显示出它的实例,不可能看到可用逻辑驱动器的任何具体信息,只能看到对应每一个可用逻辑驱动器的Win32_LogicalDisk条目)。现在,窗口的右边显示出Win32_logicalDisk类的属性。可以看到,属性的值都为空,这是因为我们正在查看的是一个类,而不是类的具体实例。要显示出Win32_LogicalDisk类的实例,点击右边上面的Instances按钮(右数第四)。

      点击Instances按钮之后,窗口显示出当前机器上所有逻辑驱动器的实例,包括网络逻辑驱动器。点击设备ID为“C:”的实例,显示出图四的结果。右边窗格包含了当前实例的属性和方法,当前逻辑驱动器的名称显示在右边窗格的上方。

      利用脚本可以修改这些属性或调用这些方法。如果对某个属性的含义不太清楚,只需选择Win32_LogialDisk类或Win32_LogicalDisk.DeviceID="C:"实例,再点击Help按钮。大多数对象的属性和方法都有详细的说明。

     

    WMI功能

       现在很多朋友仍然在使用管理员账号密码为空的系统,这样就为黑客制造了可乘之机,其中系统自带的WMI是最方便的入侵通道。WMI(Windows管理规范)作为一项Windows管理技术,方便用户对计算机进行远程管理。但是它的易用性也导致了系统的安全性大幅下降。让用户的电脑除了自己账号密码的保护外再没有什么安全保护措施。本期我们就向大家介绍“菜鸟”级的黑客都可以轻易利用的入侵通道——WMI(Windows管理规范)。

      小知识:什么是WMI?

      WMI是一项核心的Windows管理技术,WMI作为一种规范和基础结构,通过它可以访问、配置、管理和监视几乎所有的Windows资源,比如用户可以在远程计算机器上启动一个进程;设定一个在特定日期和时间运行的进程;远程启动计算机;获得本地或远程计算机的已安装程序列表;查询本地或远程计算机的Windows事件日志等等。

      本质善良的WMI

      从WMI本来的功能看,它是为了让计算机的管理更容易,同时方便管理员远程操作系统而产生的,那么它又怎么会为“菜鸟”级的入侵者提供方便呢?

      一般情况下,在本地计算机上执行的WMI操作也可以在远程计算机上执行,只要用户拥有该计算机的管理员权限。如果用户对远程计算机拥有权限并且远程计算机支持远程访问,那么用户就可以连接到该远程计算机并执行拥有相应权限的操作。

      WMI能够成为远程控制下的一个合法通道,有了这个通道,入侵者不需要对自己进行伪装,不必再为探测出对方账号的密码为空后,找不到连接对方系统的通道而发愁。只要进行简单几个步骤就可以轻易地入侵到别人的电脑中。下面,我们就来看看,到底该如何利用WMI通道。

      WMI被利用为虎作伥

      前面介绍了WMI的原理,下面我们实际了解下,如何通过WMI进行入侵。在网上,有很多利用WMI的小工具,这里我们就以rots.vbs工具进行简单的演示,看一个“菜鸟”黑客如何轻易地入侵。

      1.扫描135端口

      要寻找可以通过WMI入侵的远程计算机,只要对135端口进行扫描就可以了。因为WMI服务默认打开的就是135端口。我们本次实例采用的是NTscan扫描工具,因为它不但可以对IPC$、SMB、WMI这些信息进行扫描,同时还可以对扫描到的远程账户进行弱口令猜测,功能相对来说比较强大。

      运行NTscan,在程序窗口的“配置”区域中进行设置。首先在“起始IP”和“结束”选项中输入扫描的IP地址范围,接着选择“WMI扫描”选项,并且在“扫描打开端口的主机”选项后输入“135”,最后点击“开始”按钮就开始进行扫描(如图)。 

      2.开启终端服务

      找到可以入侵的远程计算机以后,就可以开始入侵操作了。首先使用的工具是一个名为rots.vbs的脚本程序,通过它可以开启远程计算机的终端服务。脚本会自动判断目标系统类型,如果不是Windows 2000 Server及以上版本的系统,脚本就会提示是否要取消操作。因为Windows 2000 Pro以下版本不能安装终端服务。

      然后是开启终端服务。开启工具的使用方法非常简单,命令格式为:cscript. rots.vbs <目标IP> <用户名> <密码> [服务端口] [自动重启选项]

      其中,[服务端口]和[自动重启选项]为可选参数,默认情况下,程序开启的终端服务端口为3389,如果用户需要修改,在[服务端口]选项中填入你要的端口即可,而[自动重启选项]选项则是在开启终端服务以后重启系统用的。

      举个例子:cscript.exe rots.vbs 192.168.0.6 Administrator "" 4466 /r

      上面这段实例的意思是开启192.168.0.6这台远程计算机的终端服务,并且将端口更改为4466,服务安装完成后自动重启。

      屏闭135端口防御入侵

      从上面的介绍大家都可以看出,整个过程中使用的端口都是135。所以为了防止别人通过WMI进行入侵,我们可以使用防火墙对135端口进行屏蔽,这样就可以达到防范类似的入侵。用户加强自己的账号密码强度,也可以有效防范入侵。

      关闭135端口的方法

      我们使用到十六进制的编辑器,比如:WINHEX、UltraEdit等软件。运行UltraEdit,通过工具栏上的“打开文档”按钮找到系统SYSTEM32文件夹下的rpcss.dll。接着点击“搜索”菜单中的“查找”命令,在弹出的窗口中查找“3100330035”这个字符串,找到后将它替换为“3000300030”,并另存为其他的文件目录中,建议保存在C盘根目录下。

      重新启动系统,用启动盘启动到DOS状态下,进入C盘后运行:copy rpcss.dll c:\windows\system32\rpcss.dll,然后重新启动计算机,就会发现135端口已经被关闭。

      使用网络防火墙也可以通过端口限制的手段进行屏蔽135端口。我们以天网网络防火墙为例。打开天网防火墙界面,依次点击“IP规则管理→增加规则”,然后在弹出的窗口界面中,在数据包方向中选择“接收或者发送”,在数据包类型中选择“TCP”,最后在本地端口中输入“135”,然后就是确定退出,最后保存规则即可。以后如果有数据从135端口进行传输,天网就会自动进行拦截。

  • If...Then...ElseIf

    2010-03-24 19:59:14

    If...Then...ElseIf adds some flexibility to your ability to make decisions by using VBScript. If...Then enables you to evaluate one condition and take action based on that condition. By adding ElseIf to the mixture, you can make multiple decisions.

     

     

    Example:Get the CPU informaiton

    Option Explicit
    'On Error Resume Next
    Dim strPrompt
    Dim strTitle
    Dim intBTN
    Dim intRTN
    Dim FSO
    strPrompt = "Do you want to run the script?"
    strTitle = "MSGBOX DEMO"
    intBTN = 3
    intRTN = MsgBox (strPrompt,intBTN,strTitle)
    If intRTN = vbYes Then
    WScript.Echo "yes was pressed"
    subCPU
    ElseIf intRTN = vbNo Then
    WScript.Echo "no was pressed"
    WScript.quit
    ElseIf intRTN = vbCancel Then
    WScript.Echo "cancel was pressed"
    WScript.quit
    Else
    WScript.Echo intRTN & " was pressed"
    WScript.quit
    End If

    Sub subCPU()
    Dim strComputer
    Dim cpu
    Dim wmiRoot
    Dim objWMIService
    Dim ObjProcessor
    strComputer = "."
    cpu = "win32_Processor='CPU0'"
    wmiRoot = "winmgmts:\\" & strComputer & "\root\cimv2"
    Set bjWMIService = GetObject(wmiRoot)
    Set bjProcessor = objWMIService.Get(cpu)
    If objProcessor.Architecture = 0 Then
      WScript.Echo "This is an x86 cpu."
    ElseIf objProcessor.Architecture = 1 Then
      WScript.Echo "This is a MIPS cpu."
    ElseIf objProcessor.Architecture = 2 Then
      WScript.Echo "This is an Alpha cpu."
    ElseIf objProcessor.Architecture = 3 Then
      WScript.Echo "This is a PowerPC cpu."
    ElseIf objProcessor.Architecture = 6 Then
      WScript.Echo "This is an ia64 cpu."
    Else
      WScript.Echo "Cannot determine cpu type."
    End If
    End Sub

     

    change the If...Then...ElseIf to Select Case...Case...End Select

    Option Explicit
    'On Error Resume Next
    Dim strComputer
    Dim wmiRoot
    Dim wmiQuery
    Dim objWMIService
    Dim colItems
    Dim objItem

    strComputer = "."
    wmiRoot = "winmgmts:\\" & strComputer & "\root\cimv2"
    wmiQuery = "Select DomainRole from Win32_ComputerSystem"

    Set bjWMIService = GetObject(wmiRoot)
    Set colItems = objWMIService.ExecQuery _
      (wmiQuery)
    For Each objItem in colItems
      WScript.Echo funComputerRole(objItem.DomainRole)
    Next

    Function funComputerRole(intIN)
     Select Case intIN
      Case 0
        funComputerRole = "Standalone Workstation"
      Case 1
        funComputerRole = "Member Workstation"
      Case 2
        funComputerRole = "Standalone Server"
      Case 3
        funComputerRole = "Member Server"
      Case 4
        funComputerRole = "Backup Domain Controller"
      Case 5
        funComputerRole = "Primary Domain Controller"
      Case Else
      funComputerRole = "Look this one up in SDK"
     End Select
    End Function

     

     

     

    From

    Microsoft@ VBScript. Step by Step
    By Ed Wilson

     

     

  • 走近WSH

    2010-03-24 09:43:41

    WSH  

    WSH--这个在词典中都很难找寻的名词,对许多朋友来讲也许还比较陌生。但正是WSH ,使 Windows 操作系统具备了更为强大的功能。它让我们在使用系统时拥有了许多的便利,但同时,也让我们的电脑遭遇了不少的麻烦。下面,就让我们一步步走进 WSH 的神秘世界,共同评判它的是非功过。
      一、WSH 是什么?
      WSH 是“Windows Scripting Host”的缩略形式,其通用的中文译名为“Windows 脚本宿主”。对于这个较为抽象的名词,我们可以先作这样一个笼统的理解:它是内嵌于 Windows 操作系统中的脚本语言工作环境。
      Windows Scripting Host 这个概念最早出现于 Windows 98 操作系统。大家一定还记得 MS-Dos 下的批处理命令,它曾有效地简化了我们的工作、带给我们方便,这一点就有点类似于如今大行其道的脚本语言。但就算我们把批处理命令看成是一种脚本语言,那它也是 98 版之前的 Windows 操作系统所唯一支持的“脚本语言”。而此后随着各种真正的脚本语言不断出现,批处理命令显然就很是力不从心了。面临这一危机,微软在研发 Windows 98 时,为了实现多类脚本文件在 Windows 界面或 Dos 命令提示符下的直接运行,就在系统内植入了一个基于 32 位 Windows 平台、并独立于语言的脚本运行环境,并将其命名为“Windows Scripting Host”。WSH 架构于 ActiveX 之上,通过充当 ActiveX 的脚本引擎控制器,WSH 为 Windows 用户充分利用威力强大的脚本指令语言扫清了障碍。
      再具体一点描述:你自己编写了一个脚本文件,如后缀为 .vbs 或 .js 的文件,然后在 Windows 下双击并执行它,这时,系统就会自动调用一个适当的程序来对它进行解释并执行,而这个程序,就是 Windows Scripting Host,程序执行文件名为 Wscript.exe (若是在命令行下,则为 Cscript.exe)。
      WSH 诞生后,在 Windows 系列产品中很快得到了推广。除 Windows 98 外,微软在 Internet Information Server 4.0、Windows Me、Windows 2000 Server,以及 Windows 2000 Professional 等产品中都嵌入了 WSH。现在,早期的 Windows 95 也可单独安装相应版本的 WSH。(附:各种版本 WSH 的安装程序可以从
    http://msdn.microsoft.com/scripting 站点下载)。
      二、WSH 有什么用?
      WSH 的设计,在很大程度上考虑到了“非交互性脚本(noninteractive scripting)”的需要。在这一指导思想下产生的 WSH,给脚本带来非常强大的功能,例如:我们可以利用它完成映射网络驱动器、检索及修改环境变量、处理注册表项等工作;管理员还可以使用 WSH 的支持功能来创建简单的登陆脚本,甚至可以编写脚本来管理活动目录。
      而事实上,上述功能的实现,均与 WSH 内置的多个对象密切相关,这些内置对象肩负着直接处理脚本指令的重任。因此,我们也可以通过了解 WSH 的内置对象来探寻 WSH 可以实现的功能。
      图 1 是 WSH 的内置对象构成情况。
      从图中我们可以看出,WSH 共有 14 个内置对象,它们各自有着明确分工。具体而言,位于最底部的 Wscript. ,主要作用是提取命令行变量,确定脚本文件名,确定 WSH 执行文件名(wscript.exe 还是 cscript.exe),确认 host 版本信息,创建、关连及分离 COM 对象,写入事件,按程序结束一个脚本文件的运行,向默认的输出设备(如对话框、命令行)输出信息等;WshArguments 的作用是获取全部的命令行变量; WshNamed 负责获取指定的命令行参数集;WshUnnamed 负责获取未经指定的命令行参数集;WshNetwork 的主要作用是开放或关闭网络共享,连接或断开网络打印机,映射或取消网络中的共享,获取当前登陆用户的信息;WshController 可以创建一个远程脚本对象;WshRemote 可以实现网络中对计算机系统的远程管理,也可按计划对其它程序/脚本进行处理;WshRemote Error 的作用在于:当一个远程脚本(WshRemote 对象)因脚本错误而终止时,获取可用的错误信息;WshShell 主要负责程序的本地运行,处理注册表项、创建快捷方式、获取系统文件夹信息,处理环境变量;WshShortcut 主要用于按计划创建快捷方式;WshSpecialfolders 用于获取任意一个 Windows 特殊文件夹的信息;WshURLShortcut 用于按程序要求创建进入互联网资源的快捷方式;WshEnvironment 用于获取任意的环境变量(如 WINDIR, PATH, 或 PROMPT);WshScriptExec 用于确定一个脚本文件的运行状态及错误信息。
      在这些内置对象的帮助下,我们就可以利用 WSH 充分发挥 VBScript. 及 JScript. 等脚本的强大威力,极大地提高我们的工作效率。
      三、WSH 是怎样工作的?
      WSH的工作流程,实际上就是脚本文件被解析并执行的过程。我们知道,现在脚本经常会被植入网页,其中包括 HTML 页面(客户机端)和 ASP 页面(服务器端)。对于植入 HTML 页面的脚本,其所需的解析引擎会由 IE 这样的网页浏览器载入;对于植入 ASP 页面的脚本,其所需的解析引擎会由 IIS(Internet Information Services)提供。
      而对于出现在 HTML 和 ASP 页面之外的脚本(它们常以独立的文件形式存在),就需要经由 WSH 来处理了。在这里要插一句“废话”:WSH 的正常工作的前提,是你必须安装了微软 3.0 或更高版本的 IE,因为 WSH 在工作时会调用 IE 中的 VBScript. 和 JScript. 解析引擎。
      现在,就让我们来看看脚本文件经由 WSH 执行的过程。为了更加直观,笔者根据有关资料绘制了一幅工作流程图(图2),从图中大家能对 WSH 在脚本文件运行中所起到的作用有个理性认识。对于这个流程图,还需要补充两点:1、图中第(2、3)步,WSH 根据脚本文件后缀名,到系统注册表中查询所需的脚本引擎时,VBScript. 和 JScript. 两种语言的解析引擎是 Windows 系统中原有的,而其它脚本语言的解析引擎,如 PERL、TCL等,需要用户另行定义;2、第(5)步执行脚本命令时,一些脚本指令会使用到 WSH 内置对象所提供的服务(参见本文第二部分),例如处理注册表项。这时,脚本指令就会向 WSH 提出请求,并由 WSH 完成所需任务。也正是在这一步,WSH 的功用得到了淋漓尽致的发挥。
      四、WSH 怎么用?
      谈到这个问题,就不太好讲了。正如前面所述,WSH 实际上是一个脚本语言的运行环境,它之所以具备强大的功能,是在于充分挖掘了脚本语言的潜力。因此,如果抛开脚本语言而空谈 WSH ,那实际上就没有了意义。而如果再展开来讲述脚本语言,显然就离开了今天的主题。
      在这种情况下,只好采取一种折衷的方法:给大家推荐几个脚本文件利用 WSH 执行任务的实例,希望大家能通过这些例子对 WSH 的使用有一个初步的了解。
      脚本文件的编写十分方便,你可以选用任意一个文字编辑软件进行编写,写完后,你只需将它保存为 WSH 所支持的文件名就行了(如 ..js 文件、.vbs 文件)。最常用的编辑器当然就是我们的记事本(Notepad)了,下面的实例都是以它作为工具编写的。
      准备好了吗?让我们先来看一个最简单的例子吧。打开记事本,在上面写下:
      WScript.Echo("走近 WSH")
      好了,将它保存为以 ..vbs 或 .js 为后缀名(可千万不要弄成了 ..txt)的文件并退出记事本。双击执行这个文件,看看结果吧,是不是很有意思?
      有了第一印象后,我们继续往下看。
      这一次,我们要利用 WSH 完成一次创建十个文件夹的工作。代码如下:
      dim objdir
      set bjdir=wscript.createobject("scripting.filesystemobject")
      for k=1 to 10
      anewfolder="c:\chapter" & k
      objdir.createfolder(anewfolder)
      next
      同样,将它存为 .vbs 文件并退出。运行后,我们会发现,C 盘根目录下一次性多出了十个新文件夹。
      最后,再举一个在服务器上的运用。下面的代码将帮助你重新启动指定的 IIS 服务:
      ' define a constant for stopped services
      Const ADS_SERVICE_STOPPED = 1
      ' get an ADSI object for a computer
      Set bjComputer = GetObject("WinNT://MYCOMPUTER,computer")
      ' get an object for a service
      Set bjService = objComputer.GetObject("Service","MYSERVICE")
      ' check to see if the service is stopped
      If (objService.Status = ADS_SERVICE_STOPPED) Then
      ' if the service is stopped, then start it
      objService.Start
      End If
      将它以 startsvc.vbs 为名保存在 C: 盘根目录。并通过如下命令执行:CSCRIPT. C:\STARTSVC.VBS 。运行后,经你指定的 IIS 服务项将被重新开启。
      已经举了三个例子,其实,在 Windows 的 samples 目录下,有个 WSH 文件夹,那里面有不少很具代表性的 .vbs 和 .js 脚本文件。大家有空可以打开来看看,相信会受益匪浅的。
      此外,利用 WSH ,我们还可以自己编写脚本文件来提高网络管理方面的效率。但由于受条件限制,本人在这方面的使用心得并不多,因此也就不好多说了^_^。不过,网上这方面现成的代码倒是很多,大家有兴趣可以去研究一下。
      五、WSH 有不足吗?
      答案当然是肯定的。任何事物都有两面性,WSH 也不例外。应该说,WSH 的优点在于它使我们可以充分利用脚本来实现计算机工作的自动化;但不可否认,也正是它的这一特点,使我们的系统又有了新的安全隐患。许多计算机病毒制造者正在热衷于用脚本语言来编制病毒,并利用 WSH 的支持功能,让这些隐藏着病毒的脚本在网络中广为传播。2000年曾名燥一时的 I Love You 便是一个典型代表。因此,大家对于来历不明、尤其是邮件附件里的一些脚本文件还是应该保持戒备。至于相应的防范措施,笔者在别的文章中已有论述,在此就不再罗嗦了。
      以上文字,希望能对大家认识 WSH 有所帮助。在运用过程中,大家若有什么心得或发现,别望了一起分享哦。

    原文http://www.cnii.com.cn/20040423/ca240413.htm

  • 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

     

     

1085/6<123456>
Open Toolbar