How I may help
LinkedIn Profile Email me!
Call me using Skype client on your machine

Reload this page Batch Scripts for Windows

This page summarizes use of Microsoft Windows Script Technologies to perform activites without operation intervention by coding scripts run on an interpreter or “host” such as Active Server Pages (ASP), Internet Explorer, or Windows Script Host.

Wisk away sound

 

Topics this page:

  • Script Languages
  • Script Product Versions
  • Script Execution
  • Script Encoding
  • Script Hosts
  • Script Debugging
  • Sample Scripts
  • Objects and Methods
  • Logon Scripts
  • Resources
  • Your comments???
  •  

    Site Map List all pages on this site 
    About this site About this site 
    Go to first topic Go to Bottom of this page


    Related Topics:

  • Environment Variables
  • Javascript
  • Free Training!
  • Tech Support
  • Set screen Scripting Languages


    download Download the Visio 2000 file for this graphic

      Command Prompt .bat files

      The Microsoft Windows DOS operating system always had .bat files containing traditional DOS commandsanother page on this site File with a .Bat or .cmd extension are still used to invoke scripting hosts.

      .wsh Host Control File

      .wsh files are text documents the controls the run-time execution of scripts. Their function is analogous to the PIF file used to run older 16-bit applications. The .wsh file is created automatically when properties are set for a supported script file (below).

      Logon files (introduced with WSH 2) are read by Windows 2000 PDC's and BDC's integrated with the Windows 2000 OS. Commands within .wsh files may access system services through requests for COM components to be implemented (what interface handlers to use). Sample .wsh logon script

      .js JScript (Javascript/ECMAScript)

      JScript files (with a .js file suffix and under “JSFile” in the Registry) contain the Microsoft implementation of the ECMA 262 language specification (ECMAScript Edition 3) — also called Javascipt. Unlike VBScript, Javascript has no built-in support for reading or writing files. To remedy this, the Microsoft FSO (File System Object) model to process (detect, add, move, change, create, or delete) individual of a collection of files, folders, and drives. For security, the Internet Explorer default security settings do not allow client-side use of FSO objects. The Scripting type library (Scrrun.dll) supports text file creation and manipulation through the TextStream object. JScript Sample code:

        // Instantiate a File System ActiveX Object:
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        // Invoke the method:
        var a = fso.CreateTextFile("c:\\testfile.txt", true);
        // Do something with it:
        a.WriteLine("This is a test.");
        // Close the connection:
        a.Close();

      The MS.NET (5.6) version of JScript developed in conjunction with ECMAScript Edition 4 includes access to the .NET Frameworks as well as code compilation, typed and typeless variables, classes (with inheritance, function overloading, property accessors, etc.), packages, and cross-language support.

      JScript Language Reference (from the Windows 2000 Professional CD. folder VALUADD/ MSFT/ XTRADOCS)

      .vbs VBScript

      VBScript files (with a .vbs file suffix and under “VBSFile” in the Registry) is officially called “Microsoft® Visual Basic® Scripting Edition” language. It can use the same Script Components to reference COM components used to control Microsoft's IIS web servers.

      But unlike VBA, VBScript v5 supports run-time Regular Expression (RegExp), Eval of assignment expressions and and Evaluate on comparison expressions that tests whethre variables have the same value.

      VBScript Language Reference (from the Windows 2000 Professional CD folder VALUADD/ MSFT/ XTRADOCS)

      toolRun sample VBScript file viewall.vbs (a compilation of .vbs files from the Windows 2000 Resource Kit CD)

      .wsf Windows Script properties Files

      Provide flexibility. Only from within .wsf files can ...

      • multiple scripting languages (and associated script host engines) be called.
      • optional <package> element enclose multiple <job> definitions.
      • XML elements be used.

      Other Script Languages

    • A Perl interpreter is available from Activestate.com More on Perl
    • A Python interpreter is available from Python.org

      .wsc Script Components

      .wsc (Windows Script component) files use XML (Extensible Markup Language) elements to define the properties, methods, and events which are exposed to the <public>, The Automation handler component makes sure the correct methods are called correctly when needed by host applications.

      COM requests are dispatched by the Scrobj.dll run-time component (COM inproc server). Compiled Interface handler components implement specific COM interfaces, such as DHTML Behaviors. Thus, the complexities of COM, including the implementation of such COM-standard interfaces as IUnknown, are embedded in the various interface handlers.

      XML elements in .wsc files may <reference> “type libraries” containing pre-built COM components.

      Introducing Windows Script Components (from the Windows 2000 Professional CD folder VALUADD/ MSFT/ XTRADOCS)


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Windows Scripting Technologies Product Version History

      Windows Vista introduces the PowerShell [subscribers only]

    • As of this writing, the most current version is 733,792 bytes on 10/18/2001 V5.6. Download it. It's described in 09/06/2001 1,351,013 bytes from scrdoc56en.exe Script56.chm.

    • .NET Frameworks Beta 2 users should download this 9/10/2001 patch.

    • WSH 2 provided with Windows 2000 introduced file includes, tools support, echo command, script Debugger.

    • WSH 1 provided with Windows 98 and NT4 introduced encoded versions VBEFile and JSEFile self-contained procedures message/dialog boxes looping (iterative) logic

      To convert .BAT files to WSH scripts entails replacing NT's net.exe commands with corresponding WSH objects, methods, and properties.

      Klaus Graefensteiner has several good articles on use of PowerShell mash-ups, including Extreme Mesh-Up using NUnit, PSExec, PowerShell and NetMon 3.2 to automate http traffic monitoring

      TABLE 1: WSH Counterparts to Batch File Commands
      Logon
      Script Task
      Batch File Solution WSH Solution
      Determining directory and disk space utilization Resource kit utilities diruse.exe and diskuse.exe VBScript's FileSystemObject
      Performing file I/O Command redirection symbols(e.g., >, >>, <, |) and command filters (e.g., find, more, sort) VBScript's FileSystemObject
      Using environment variables Command processor's Set command and %EnvironmentVariable% construct WSH Shell object's Environment property
      Handling errors ERRORLEVEL environment variable VBScript's Err object
      Accepting user input Command-line arguments the script accesses via %1, %2, %3, etc. Command-line arguments the script accesses via WScript's Arguments property, or arguments the user enters interactively and the script accesses via VBScript's InputBox function
      Providing script output Command processor's Echo command WScript's Echo method, WSH Shell object's Popup method, or VBScript's MsgBox function
      Establishing network connections NT's net.exe commands WSH Network object
      Performing Registry I/O Resource kit utility reg.exe WSH Shell object's RegDelete, RegRead, and RegWrite methods
      Running external commands Command or utility name WSH Shell object's Run method
      Searching via regular expressions Command redirection symbols (e.g., <, |) and command filters (e.g., find, findstr) Forthcoming VBScript RegExp object
      Manipulating groups and users NT's net.exe commands and a variety of resource kit and third-party utilities ADSI


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Script Execution Security

      Do this! Click here to have your Internet Explorer (IE browser) Open (and Run) the wsh_info.vbs script file which displays information about your computer in a pop-up box. These are called intrinsic objects.

      One way to disable the execution of ALL such files is from within Windows Explorer. Right-click on a .vbs file (of Type “VBScript Script File”) and select Open With. Instead of being executed by the “Microsoft Windows Based Script Host” program, Choose Program... and select a program that cannot execute files, such as “Notepad” or “Wordpad”. This will cause the script file to be opened for editing.

      This action changes the Open registry key under HKEY_CLASSES_ROOT\ VBSFile\ Shell to

        %SystemRoot%\System32\Notepad.exe %1 rather than
        %SystemRoot%\System32\CScript.exe "%1" %*

      With this change, if you need to execute a VBScript, in MS Windows Explorer, right click on the file it and select Execute VBScript.

      Repeat the above actions for two other extensions:

        .js (in Reg. key HKCR\JSFile)
        .wsh (in Reg. key HKCR\WSHFile)

      HTML Applications (HTAs) introduced with IE5 are "not subject to the same security constraints as Web pages"

      Hackers exploited this back door with the Winmain.exe exploit

      By default, Windows automatically enables HTA on bootup via registry entry HKLM / SOFTWARE / classes / htafile / Shell / Open / Command value C:\WINNT\System32\mshta.exe "% 1" %* Since this runs in the trusted Local zone, parses and runs scripts despite firewall and/or IE restrictions.

      tool Free HTAStop2003 blocks and permits HTA apps. $60 IEClean from Privacy Software prevents additional exploits.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Script Encoder

      tool Microsoft provides a Script Encoder command-line tool (screnc.exe) download to encode (not really compile) scripts to make them more difficult to view or modify. Encoded scripts are also quicker to download.

      An example encoded script to be inserted between <HEAD> tags in a HTML file:


        <SCRIPT language="JScript.Encode">
        <!--//
        //**Start Encode**mDkWP7nDb0zZKD.n1YAMGhk+Dv ZKD.n1Y AMGhk+Dv
        //-->
        </SCRIPT>

      The function defined by this script would simply not execute if even one character of the encoding is changed during transmission. So you may want to add code to detect whether script code was actually executed.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Scripting Hosts

      There are two separate executable files to read and execute scripts:

      • cscript.exe for output to command window (MS DOS prompt) and stdout
      • wscript.exe for interactive interface with graphical dialog boxes

      Only cscript.exe can use the ERRORLEVEL built-in environment variable that contains the exit code value from the last command run using the command processor (cmd.exe).

      Host Settings and .wsh Script Control Properties

      The screen to the right is the script Host Settings page that appears when wscript.exe is Run with default (no) parameters.

      With WSH 5.6, you can define different settings in a .wsh script control file for each script, use one of these procedures:

      • Interactively change options for all scripts:
        • Checking "Stop script after specified number of seconds" and selecting “5” second2; and
        • Checking "Display logo when scripts executed in command console"

      • From within Windows Explorer, right-clicking on a .vbs or .js script file. This creates a file with the same name as the script file, but with .wsh file extension and contents such as this:

        [ScriptFile]
        Path=C:\WINNT\Samples\WSH\sample.vbs
        [Options]
        Timeout=5
        DisplayLogo=1
        BatchMode=0
        
      • Run this command:
        cscript sample.vbs //T:5 //Logo //S

        Other options can be obtained with this command:
        cscript /?

        The result of the above command:

          Usage: CScript scriptname.extension [option...] [arguments...]
          
          Options:
           //B         Batch mode: Suppresses script errors and prompts from displaying
           //D         Enable Active Debugging
           //E:engine  Use engine for executing script
           //H:CScript Changes the default scripting host to CScript.exe
           //H:WScript Changes the default scripting host to WScript.exe (default)
           //I         Interactive mode (default, opposite of //B)
           //Job:xxxx  Execute a WSF job
           //Logo      Display logo (default)
           //Nologo    Prevent logo display: No banner will be shown at execution time
           //S         Save current command line options for this user
           //T:nn      Time out in seconds:  Maximum time a script is permitted to run
           //X         Execute script in debugger
           //U         Use Unicode for redirected I/O from the console (CScript only)
          

      Windows Scripting Host Reference offers more information.


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Script Debuggers

      The scripting engines cscript and wscript.exe call to parse VBScript and JScript scripts are the same engines used by Internet Explorer and IIS/ASP.

      By default, the Internet Explorer Script Debugger is invoked.

      "<SCRIPT>" must be placed at the beginning and "</SCRIPT>" at the end of the file.

      Visual Studio's Visual InterDev product is better because it handles

      • Set breakpoints
      • Step through scripts
      • View and change values
      • View call stack

      This command enables error messages and launching of the script debugger when a syntax or run-time error is encountered in a Windows Script file:

        <?job error="true" debug="true" ?>

     

     
    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Sample Scripts

      A command in PerlScript:

        <script language=PerlScript RUNAT=Server>
        sub PerlSpit {
            my $str = @_[0];
            $WScript->Echo($str);
        }
        </script>

      A comparison of JScript and VBScript commands using the object.method syntax:

        <script language="VBScript">
            wscript.echo "Hello"
            PerlSpit "Hello 2"
        </script>
        <script language="JScript">
            wscript.echo("Hello");
            PerlSpit("Hello 2");
        </script>

      Escape characters

      Set screen Sample .wsh Logon VBScript

        ' Add/Remover Printers and shares:
        set WshNetwork=CreateObject ("Wscript.Network")
        WshNetwork.AddWindowsPrinterConnection "lpt1", "\\servername\lasername"
        WshNetwork.MapNetworkDrive "z:", "\\servername\sharename"
        WScript.Echo "You are now connected to the network printer and file share"
        ' Read, write, delete registry values and entries as WshShell objects (with valid administrator permissions):

        ' Read and write Drives, Folders, Files collections & objects and the TextStream object:
        ' GetAbsolutePathName, etc.
        set objFS=CreateObject ("Script.FileSystemObject")
        set listFile = obFS.OpenTextFile ("c:\windows\system\oeminfo.ini")
        do while listFile.AtEndOfStream <> True
            Wscript.Echo listFile.ReadLine
        loop


    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Message Dialog Box

      VBScript provides for a more sophisticated dialog box:

      Syntax:
      result = MsgBox( prompt, buttons, title)

      Example: To show a question icon with OK and Cancel buttons in the foreground:
      result = MsgBox("Please click a button", vbQuestion + vbOKCancel + vbSystemModal, "XXX Whatever selection")

      buttons result
      1
      vbOK
      3
      vbAbort
      4
      vbRetry
      5
      vbIgnore
      6
      vbYes
      7
      vbNo
      2
      vbCancel
      0 or vbOKOnly
      OK
      1 or vbOKCancel OK Cancel
      2 or vbAbortRetryIgnore Abort Retry Ignore
      3 or vbYesNoCancel Yes No Cancel
      4 or vbYesNo Yes No
      5 or vbRetryCancel Retry Cancel
      16 or vbCritical Stop icon.
      32 or vbQuestion Question mark icon.
      48 or vbExclaimation Exclaimation point icon.
      64 or vbInfomation Infomation icon.
      256 or vbDefaultButton2 Sets the focus to the second button.
      512 or vbDefaultButton3 Sets the focus to the third button.
      4096 or vbSystemModal Presents the dialog box in the foreground.

    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen Input Dialog Box VBScript

      VBScript Syntax:
      result = InputBox( prompt[, [title], [default], [xpos], [ypos]])

      Example: To prompt user for a text string:
      result = InputBox("Please input report title", "", "Sample InputBox input")

      Set screen Use ADSI to add Users to a Group from an Excel file

        set objDS=GetObject("@Namespace!Company\TopOU\NextLowerOU")
        set objGroup= GetObject("@Namespace!Company\Group1")
        for each objUser in objDS
            objGroup.GeneralInfo.Members.Add (objUser)
        next objUser

    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Objects

      Set screen Built-In Objects

      • Sleep method suspends script for n seconds. This does not chew up CPU usage like a dummy loop does.
      • Sendkeys method emulates keyboard hits by user. Used to automate older Windows applications.
      • AddWindowsPrinter
      • StdIn/StdOut file system stid object.
      • Event Logging
      • Drag and Drop support process a file by dragging it dropping it over the script file icon.
      • Shell Objects

      Set screen XML Elements

      • <SCRIPT> language - can switch between
      • <OBJECT> instance of COM object
      • <REFERENCE> typelibrary support
      • <JOB> for multiple job ID's in a single script file command line switch to select a particular job to run <PACKAGE>


    Go to Top of this page.
    Previous topic this page
    Next topic this page

      Set screen ADSI/(Active Directory Service Interfaces) Directory COM Objects

      • Standard container objects: namespaces, country, locality, organization, organizational unit, domain, computer
      • Standard leaf objects: user, group, alias, service, print queue, print device, print job, file service, file share, session, resource (cannot contain other ADSI objects)

     


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen Logon Scripts

      Make Windows wait for scripts to finish

      To make Windows NT/2000/XP wait for logon scripts to complete before it starts the user shell (rather than letting the scripts should run asynchronously), find registry key

        [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]

      (HKEY_LOCAL_MACHINE is application for all users. So to limit this restriction per user, add the value to HKEY_CURRENT_USER)

      Edit or create the DWORD value 'RunLogonScriptSync' 0 = disabled, 1 = enabled

      http://www.win2000mag.com/Articles/Index.cfm?Articleid=4760

      Sams Teach Yourself Windows Script Host in 21 Days by Fredell, Thomas L.; Morrison, Michael ISBN: 067231374X Indianapolis, Ind. Sams, 1999.

     


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Set screen More Resources

     


    Go to Top of this page.
    Previous topic this page
    Next topic this page

    Portions ©Copyright 1996-2010 Wilson Mar. All rights reserved. | Privacy Policy |


    How I may help

    Send a message with your email client program


    Your rating of this page:
    Low High




    Your first name:

    Your family name:

    Your location (city, country):

    Your Email address: 



      Top of Page Go to top of page

    Thank you!