WSH                              
*     Microsoft Stuff
  3/13/26   WSH
                                 
   
  Home https://www.makeuseof.com/tag/batch-windows-scripting-host-tutorial/ SS64
  How To's
  Misc Available languages include JScript, VBA, and VBscript.
  Networking It's also possible to write scripts in Perl, Python, PHP, Ruby or even Basic
  Windows  if you have the right implementation with the right scripting engine.
  Glossary
  Excell helloworld.vbs
  Examples wscript.echo   "Hello World"
  Outlook wscript.quit
  Paint Shop Pro
  Skype For the most flexibility, place <job> and <script language="VBScript"> (or whatever language you choose) 
  WSH around each segment of code in your file, and save it as a .wsf file. see Hello_World.wsf
  DOS This way, so long as you enclose the code in the defined script language tags, you can use multiple languages in the same file.
   
   
                  https://flylib.com/books/en/2.442.1/    
    Part I - Introducing the WSH and VBScript
   
    Getting Started with the WSH and VBScript
   
click to expand
    WSH Scripting Engines
    VBScript
    JScript
    3rd Party
   
    WSH Script Execution Host
    CScript.exe
    Wscript.exe
   
   
    WSH Core Object Model provides VBScript with direct access to Windows resources.
    ( WSH.OSX ) Exposes the Win OS objects in a format that allows scripts to view, access, and manipulate them.
   
    Windows Resources (objexts)
    The Windows operating system can be viewed as a collection of objects Windows desktop
    Windows Start Menu
    Win OS: Objects > file Windows applications
    disk drive Windows file system
    printer Windows Quick Launch Toolbar
    any resource that is part of the computer Network printers
    Network drives
    Windows registry
   
    Objects > Have associated properties and methods that scripts can then use to interact with an object,
    as well as affect its behavior or status.
   
    Object Properties Methods properties (attributes) an object-specific attribute
    ie file name copy methods (actions) built-in functions that your scripts can execute to perform an action on an object
    file ext. move
   
   
    Overview of the Windows Script Host g
   
    Working with objects   Many Windows applications, including Microsoft Office applications, expose their own object models, allowing VBScript to programmatically manipulate them.
    In addition, other VBScript execution hosts, such as Internet Explorer, provide VBScript with access to other object models. 
    The WSH core object model is quite complex and may at first seem rather daunting
   
      Object Model   is a representation of a number of related objects that provide a script or program with the ability to view and interact with each of the objects (files, disks, printers, and so on) represented in the object model.
     
click to expand
      The Core Object Model The WSH core object model provides programmatic access to Windows resources.
      There are 14 objects in the WSH core object model Each of these objects provides access to a particular category of Windows resources.
     
      Wscript object ("top level", or root) It is from this object that all other objects are instantiated
      Is automatically established during the startup of the execution host and can therefore be referenced without first being instantiated within your scripts.
     
      Provides access to a number of very useful methods ----> CreateObject(). Establishes an instance of the specified object.
      DisconnectObject(). Prevents a script from accessing a previously instantiated object.
      Echo(). Displays a text message in the Windows Console or as a popup dialog depending on which execution hosts runs the script.
      Quit(). Terminates a script's execution.
      Sleep(). Pauses the execution of a script for a specified number of seconds.
   
    Instantiation A term that describes the process of creating a reference to an object.
    In order to work with an object you must first create, or instantiate, a reference to it within your scripts.
    Publice (Exposed) Objects
    The WScript object (top level object) is referred to as a public or exposed object. The WSH core object model has three other public objects  ------> Wscript "top level (root) object" Table 2.3: WSH OBJECT PROPERTIES Table 2.4: WSH OBJECT METHODS
      WshController
    Each of these three objects must be instantiated within your scripts using the WScript object's CreateObject() method     WshShell, Property Description Method Description
      WshNetwork Arguments Sets a pointer reference to the WshArguments collection. AddPrinterConnection() Creates printer mappings
    AtEndOfLine Returns either true or false depending on whether the end-of-line maker has been reached in the stream. AddWindowsPrinterConnection() Creates a new printer connection
    All of the other objects in the WSH core object model can only be instantiated by using properties or methods associated with the WScript, WshController, WshShell, and WshNetwork objects. AtEndOfStream Returns either true or false depending on whether the end of the input stream has been reached. AppActivate() Activates the targeted application Window
    Character Identifies the specific character in a line of code where an error occurs. Close() Terminates an open data stream
    Lower-Level Objects Column Returns the current column position in the input stream. ConnectObject() Establishes a connection to an object
    Table 2.1: WORKING WITH LOWER-LEVEL WSH OBJECTS WshArguments ComputerName Retrieves a computer's name. Count Retrieves the number of switches found in the WshNamed and WshUnnamed objects
    WshNamed CurrentDirectory Sets or retrieves a script current working directory. CreateObject() Creates a new instance of an object
    Object Method of Instantiation (the object properties or methods required to instantiate them)                 WshUnnamed Description Retrieves the description for a specified shortcut. CreateScript() Instantiates a WshRemote object representing a script that is running remotely
    WshArguments WScript.Arguments WshRemote Environment Sets a pointer reference to the WshEnvironment. CreateShortcut() Creates a Windows shortcut
    WshNamed WScript.Arguments.Named WshRemoteError Error Provides the ability to expose a WshRemoteError object. DisconnectObject() Terminates a connection with an object
    WshUnnamed WScript.Arguments.Unnamed WshShortcut ExitCode Returns the exist code from a script started using Exec(). Echo() Displays a text message
    WshRemote WshController.CreateScript() WshUrlShortcut FullName Retrieves a shortcut or executable program's path. EnumNetworkDrives() Enables access to network drives
    WshRemoteError WshRemote.Error WshEnvironment HotKey Retrieves the hotkey associated with the specified shortcut. EnumPrinterConnections() Enables access to network printers
    WshShortcut WshShell.CreateShortcut() WshSpecialFolders IconLocation Retrieves an icon's location. Exec() Executes an application in a child command shell and provides access to the environment variables
    WshUrlShortcut WshShell.CreateShortcut() WshScriptExec Interactive Provides the ability to programmatically set script mode. Execute() Initiates the execution of a remote script object
    WshEnvironment WshShell.Environment Item Retrieves the specified item from a collection or provides access to items stored in the WshNamed object. Exists() Determines a specified key exists within the WshNamed object
    WshSpecialFolders WshShell.SpecialFolders Length Retrieves a count of enumerated items. ExpandEnvironmentStrings() Retrieves a string representing the contents of the Process environmental variable
    WshScriptExec WshShell.Exec() Line Returns the line number for the current line in the input stream or identifies the line number within a script on which an error occurred. GetObject() Retrieves an Automation object
    Name Returns a string representing the name of the WScript object. GetResource() Retrieves a resource's value as specified by the tag
    Set used to create a reference to a specified object Number Provides access to an error number. LogEvent() Writes a message in the Windows event log
    & concatenation character Path Returns the location of the folder where the CScript or WScript execution hosts reside. MapNetworkDrive() Creates a network drive mapping
    _ The _ character is a continuation character and is used to indicate that a statement is continued on the next line. ProcessID Retrieves the process ID (PID) for a process started using the WshScriptExec object. Popup() Displays a text message in a popup dialog
    ScriptFullName Returns an executing script's path. Quit() Terminates, or ends, a script
    Constant a VBScript construct that contains information that does not change during the execution of a script ScriptName Returns the name of the executing script. Read() Retrieves a string of characters from the input stream
    Source Retrieves the identity of the object that caused a script error. ReadAll() Retrieves the s string that is made up of the characters in the input stream
    built-in constants VBScript provides a collection of built-in constants, such as the vbTab and vbCrLf constants SourceText Retrieves the source code that created the error. ReadLine() Retrieves a string containing an entire line of data from the input stream
    SpecialFolders Provides access to the Windows Start menu and desktop folders. RegDelete() Deletes a registry key or value
    Status Provides status information about a remotely executing script or a script starting with Exec(). RegRead() Retrieves a registry key or value
    Working with Object Methods StdErr Enables a script to write to the error output stream or provides access to read-only error output from an Exec object. RegWrite() Creates a registry key or value
    StdIn Enables read access to the input stream or provides access to the write-only input stream for the Exec object. Remove() Deletes the specified environmental variable
    WshShell object provides access to a number of Windows resources StdOut Enables write access to the output stream or provides access to the write-only output stream of the Exec object. RemoveNetworkDrive() Deletes the connection to the specified network drive
    The Windows application log TargetPath Retrieves a shortcut's path to its associated object. RemovePrinterConnection() Deletes the connection to the specified network printer
    The Windows registry UserDomain Retrieves the domain name. Run() Starts a new process
    ---> Any Windows command-line command ??  could make "log" entries using this ?? UserName Retrieves the currently logged-on user's name. Save() Saves a shortcut
    Version Retrieves the WSH version number. SendKeys() Emulates keystrokes and sends typed data to a specified window
    WindowStyle Retrieves a shortcut's window style. SetDefaultPrinter() Establishes a default Windows printer
    Configuring WSH Execution Hosts WorkingDirectory Returns the working directory associated with the specified shortcut. ShowUsage() Retrieves information regarding the way that a script is supposed to be executed
    Skip() Skips x number of characters when reading from the input stream
    SkipLine() Skips an entire line when reading from the input stream
    Customizing WScript Settings for Individual Desktop Scripts Win - R (run)     Wscript Sleep() Pauses script execution for x number of seconds
    Terminate() Stops a process started by Exec()
       
    Back to the Rock, Paper, and Scissors Game    
       
    'Time for the computer to randomly pick a choice    
    Randomize Ensures that a random number is generated each time the script executes    
    GetRandomNumber = Int((3 * Rnd()) + 1) Generate a number between 1 and 3. (  the Rnd() function generates a random number between 0 and 1 )    
       
       
       
       
       
    Write() Places a string in the output stream
    WriteBlankLines() Places a blank in the output stream
    Part II - Learning VBScript & WSH Scripting WriteLine() Places a string in the output stream
   
    VBScript Basics
   
    VBScript Syntax Rules More than one VBScript statement can be placed on a single line by ending each statement with the : (colon) character.
    You can enforce case-sensitivity by adding the Option Explicit statement to the beginning of your VBScripts.
    By default, an error will halt the execution of any VBScript.
    You can prevent error from terminating a VBScript's execution by adding the On Error Resume Next statement to your VBScripts.
   
    Reserved Words you cannot use them as variables, constants, or procedure names
   
    Adding Comments Rem  '
    Also, you can add a comment to the end of any statement.
    ie MsgBox  "Thank you for playing"      ' Display a thank you message
   
    Mastering the VBScript Object Model VBScript also provides two collections of objects that you can use in your scripts. 
   
    Table 3.3: VBSCRIPT CORE OBJECTS
    Class
    Dictionary
    Err
    FileSystemObject provides a number of run-time objects your scripts can use these objects and their properties and methods to interface with the Windows file system.
    Match Dictionary
    Matches Collection Drive
    RegExp Drives Collection
    SubMatches Collection File
    Files Collection
    FileSystemObject
    Folder
    Folders Collection
   
    The WSH core object model provides access to a number of Windows resources. Absent from this model is a file system object.
    To access system files from your VBScripts, you'll need to learn how to work with VBScript's FileSystemObject object.
   
    With this object, your scripts will be able to: Check for the existence of files and folders before attempting to work with them
    Create and delete file and folders
    Open and read files
    Write or append to files
    Close files
    Copy and move files and folders
   
    Properties the VBScript run-time objects support a large number of properties
   
    Methods VBScript run-time objects also support a larger number of methods that you will find essential when working with the Windows file system. 
   
    Using VBScript Run Time Objects in Your Scripts
   
    Examining Built In VBScript Functions One of the real advantages of working with VBScript is having access to its large number of built-in functions.
    For a complete list, refer to Appendix B, "Built-In VBScript Functions."
    POPUP() Method      (ie Response = WshShl1.Popup(…...) )
    Displaying Script Output Buttons Icon Return Values
    WScript.Echo [Arg1] [,Arg2] ... Displays Displays Button
    WSH Echo() WScript.Echo "This message appears differently depending on the " 0 OK button 16 Stop icon 1 OK
    Popup() Response = WScript.Popup(StrText,[TimeToWait],[TitleBarMsg],[DialogSettings]) 1 OK + Cancel buttons 32 Question Icon 2 Cancel
    Response = WshShl.Popup("This is a text message", ," Test Script", 5) 2 Abort, Retry, + Ignore buttons 48 Exclamation Icon 3 Abort
    3 Yes, No, + Cancel buttons 64 Info Icon 4 Retry
    VBScript InputBox() InputBox(StrText[, TitleBarMsg][, default][, xpos][, ypos][, helpfile, context]) 4 Yes + No buttons 5 Ignore
    MsgBox() MsgBox(TextMsg[, buttons][, TitleBarMsg][, helpfile, context]) 5 Retry + Cancel buttons 6 Yes
    7 No
    Twip stands for Twentieth of a Point and represents a value of 1/1440th of an inch.
   
    Back to the Math Game MSGBOX() Function
    Key SendKeys Code Buttons Icon Return Values
    SendKeys  "string" shift + Constant Displays Constant Displays Constant User Clicked on
    ALT ^ 0 vbOKOnly OK button 16 vbCritical Critical Icon 1 vbOK OK
    CTRL % 1 vbOKCancel OK + Cancel buttons 32 vbQuestion Question Icon 2 vbCancel Cancel
    ENTER ~ 2 vbAbortRetryIgnore Abort, Retry, + Ignore buttons 48 vbExclamation Exclamation Icon 3 vbAbort Abort
    3 vbYesNoCancel Yes, No, + Cancel buttons 64 vbInformation Info Icon 4 vbRetry Retry
    ie  Sendkeys  "%{F4} "  send the (ctnl- F4) 4 vbYesNO Yes + No buttons 5 vbIgnore Ignore
    5 vbRetryCancel Retry + Cancel buttons 6 vbYes Yes
    7 vbNo No
   
   
    Constants, Variables, and Arrays
   
    Constants Const cTitleBarMsg = "The Three Little Pigs"
    Const cUpperLimit = 1000
    Const cMyBirthday = #11-20-64# you must use a pair of pound signs to store a date value within a constant
   
    Date and Time Constants String Constants
    Constant   Value Description Constant Value Description
    vbSunday 1 Sunday vbCr Chr(13) carriage return
    vbMonday 2 Monday vbCrLf Chr(13) + Chr(10) carriage return and a line feed
    vbTuesday 3 Tuesday vbFormFeed Chr(12) form feed
    vbWednesday 4 Wednesday vbLf Chr(10) line feed
    vbThursday 5 Thursday vbNewLine Chr(13) + Chr(10) adds a newline character
    vbFriday 6 Friday vbNullChar Chr(0) create a 0 or null character
    vbSaturday 7 Saturday vbNullString string with no value creates an empty string
    vbFirstFourDays 3 First full week with a minimum of 4 days in the new year vbTab Chr(9) horizontal tab
    vbFirstFullWeek 2 First full week of the year vbVerticalTab Chr(11) vertical tab
    vbFirstJan1 1 Week that includes January 1
    UseSystemDayOfWeek 0 Day of week as specified by the operating system
   
   
    Data Types Variants a type of variable that can contain any number of different types of data Conversion Funtions
    Subtype Description Asc()
    Boolean A variant with a value of True or False Cbool()
    Byte An integer whose value is between 0 and 255 Cbyte()
    Currency A currency value between -922,337,203,685,477.5808 and 922,337,203,685,477.5807 Cbur()
    Date A number representing a date between January 1, 100 and December 31, 9999 Cdate()
    Double A floating-point number with a range of -1.79769313486232E308 and -4.94065645841247E-324 or 4.94065645841247E-324 and 1.79769313486232E308 CDbl()
    Empty A variant that has not been initialized Chr()
    Error A VBScript error number Cint()
    Integer An integer with a value is between -32,768 and 32,767 CLng()
    Long An integer whose value is between -2,147,483,648 and 2,147,483,647 CSng()
    Null A variant set equal to a null value CStr()
    Object An object
    Single A floating-point number whose value is between -3.402823E38 and -1.401298E-45 or 1.401298E-45 and 3.402823E38
    String A string up to two billion characters long
   
   
    guidelines that you should follow when working with variables:
    Use the Option Explicit statement to enforce formal variable declaration.
    Define your variables at the beginning of your scripts in one location.
    Use the Dim statement to define each variable.
   
    Variable Scope
    scope refers to the ability to reference a variable and its assigned value from various locations within a script
    VBScript supports two different variable scopes, global and local.
    A variable with a global scope can be accessed from any location within the script. 
    A variable with a local scope can only be referenced from within the procedure that defines it.
   
   
    Procedures A procedure is a collection or group of statements that is executed as a unit.
    VBScript supports two types of procedures, subroutines and functions
   
    A variable defined outside of a procedure is global in scope
    A variable that is local in scope is a variable that is defined within a procedure.
   
    Operator
    Order of Precedence ^ Expnentiation
    - Negation
    * Multiplication
    / Division
    Integer division
    Mod Modulus
    + Addition
    - Subtraction
   
   
    Using the WSH to Work with Environment Variables
   
    There are two types of environment variables, user and computer.
    User environment variables are created during user login and provide information specific to the currently logged on user. only available when you're logged in to the computer.
    Computer environment variables, on the other hand, are created based on what Windows learns about the computer; available at all times
   
   
    Working with Collections of Related Data  
   
    For Each i In GameArray
     Message = Message & i & vbCrLf
    Next
    WScript.Echo Message
   
    ReDim Preserve TestArray(19)
   
   
    Processing Data Passed to a Script at Run Time
   
    argument  a piece of data passed to the script at the beginning of its execution
   
    Designing Scripts That Accept Argument Input
   
   
   
    Back to the story of Captain Adventure
   
   
    Conditional Logic
   
    Performing More Complex Tests with VBScript Operators
   
    If LCase(AnswerOne) = "spock" Then
   
     InStr() function 
   
    InStr([start, ]string1, string2[, compare]) If Instr(1, "kirkpicardsiscojanewayarcher", LCase(AnswerFive), 1) <> 0 Then
    Start specifies the character position in the script, from left to right, where the search should begin
    String1 identifies the string to be searched. String2 identifies the text to search for,
    compare specifies the type of search to be performed. A value of 0 specifies a binary comparison, and a value of 1 specifies a textual comparison.
   
    Game Development Stage 2
   
    Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject") The format of the OpenTextFile() method 
   
    object.OpenTextFile(filename[, iomode[, create[, format]]]) Filename is the name and path of the file to be opened or created.
    Iomode must be one of the following three constants: ForReading, a value of 1, ForWriting, a value of 2, or ForAppending,  a value of 8
    Set ScoreRpt = FsoObject.OpenTextFile("C:TempStarTrekQuiz.txt", 2, "True") Create is optional. It specifies whether a new file will be created if one does not already exist. 
    Writing ScoreRpt.WriteBlankLines(1) Specify a value of True to create a new file, if necessary, or specify False to prevent a new file from being created. 
    ScoreRpt.WriteLine("Star Trek Game Quiz") Format specifies one of the following values: True, False, or UseDefault.
    ScoreRpt.Write("===================================================") True saves the file in Unicode format
    ScoreRpt.WriteLine("===================================================") False saves the file in ASCII format
    ScoreRpt.WriteBlankLines(2) UseDefault stores the file using the operating system's default format.
   
    FileSystemObject methods
    Write BlankLines Writes the specified number of blank likes to the file.
    WriteLine Writes the specified line of text to a file and performs a carriage return.
    Write Writes the specified line of text to a file but does not perform a carriage return.
   
    ScoreRpt.Close() to close the file
   
    35 Reading a file https://stackoverflow.com/questions/3117121/reading-and-writing-value-from-a-textfile-by-using-vbscript-code
    Read line by line
   
    Processing Collections of Data
   
     Exit For
   
    The For Each Next Statement
   
    Dim FsoObject, FolderName, Member, FileList, TargtFolder For Each i In GameArray
     Message = Message & i & vbCrLf
    Set FsoObject = CreateObject("Scripting.FileSystemObject") Next
    Set FolderName = FsoObject.GetFolder("C:Temp") WScript.Echo Message
   
    For Each Member in FolderName.Files
     FileList = FileList & Member.name & vbCrLf
    Next
   
    MsgBox FileList, ," List of files in " & FolderName
   
   
    Do While
   
   
    The Final Result for the "Guess a Number" game
   
   
    Creating Shortcuts for Your Game
   
    Set WshShl = WScript.CreateObject("WScript.Shell") Set WshShl = WScript.CreateObject("WScript.Shell")
    DesktopFolder = WshShl.SpecialFolders("Desktop") TargetFolder = WshShl.SpecialFolders("Desktop")
    Set NewShortcut = WshShl.CreateShortcut(DesktopFolder & "\ Set FsoObject = CreateObject("Scripting.FileSystemObject")
    GuessANumber.lnk") Set NewShortcut = FsoObject.GetFile(TargetFolder & "\GuessANumber.lnk")
    NewShortcut.TargetPath = "c:GuessANumber.vbs" NewShortcut.Delete
    NewShortcut.Save()
   
   
    A Complete Shortcut Script
   
   
   
   
   
   
   
   
   
   
    Using Procedures to Organize Scripts
   
    Part III - Advanced Topics
   
    Handling Script Errors
    Using the Windows Registry to Configure Script Settings
    Combining Different Scripting Languages
   
    Part IV - Appendices
   
    Appendix A WSH Administrative Scripting
    Appendix B Built-In VBScript Functions
    Appendix C Whats on the CD-ROM?