VBScript

From Omnia
(Redirected from VBS)
Jump to navigation Jump to search

VBScript

"VBScript (short for Visual Basic Scripting Edition) is an Active Scripting language developed by Microsoft. The language's syntax reflects its history as a limited variation of Microsoft's Visual Basic programming language." VBScript - Wikipedia

MSDN - VBScript

Reference Guides

Tips

  • Always use Option Explicit and declare all variables [1]
  • (Temporarily) disable all On Error Resume Next lines
  • Modularize your scripts with functions and subroutines
  • Use descriptive names for variables, functions and subroutines
  • Initialize variables
  • Avoid nested functions
  • Display or log intermediate results like variable values and return codes
  • Create and use a debug window
  • Use a VBScript aware editor or IDE with built-in debugger and object browser
  • Document your scripts with useful comments
  • Use custom error handling
  • Clean up
  • Check the WSH version
  • Use a debugger, if available

Default Script Engine

CScript //H:CScript //S


This was found when running prncnfg:

Windows Script Host
Please run this script using CScript.
This can be achived by
1. Using "Cscript script.vbs arguments" or
2. Changing the default Windows Scripting Host to CScript
  using "CScript //H:CScript //S" and running the script
  "script.vbs arguments".

Syntax

NOTE: Generally VBScript is not case sensitive!

File Extensions

.VBS and .VBE

Comments

' this is a comment

Echo

Hello World:

wscript.echo("Hello World")

Variables

Variable:

Dim i

Integer:

i = 5

String

i = "test"

Boolean

i = true
i = false

Dim

Dim Version : Version = "1.0"  ' Script version
Dim strFileName
Dim var1, var2, var3

Constants

Const xl3DPie = -4102
Const xlColumns = 2

if

If [EXPRESSION] Then
   ...
   ElseIf [EXPRESSION] Then
     ...
   Else
     ...
End If
If i = true Then
  ...
End If

for

For i = 1 to 5
  wscript.echo i
Next

while

string concatenation

mystring = "hello " & "world"

line wrapping

mystring = "this is"_
  & "a wrapped line"

Exit

WScript.Quit(1)

Console Output

' VBScript which uses the root WSH COM object "WScript" to display a message and 'OK' button.
' vbscript: GUI message box with message
' cscript: console output
wscript.echo("Hello World")
cscript mytest.vbs

Console Input

strIn = wscript.stdin.readline

cscript

Difference between vbscript and cscript

"The WScript command opens separate windows for output, whereas the CScript command sends output to the Command Prompt window from which it was initiated." [2]

To force cscript:


To Change the Default Script Host:

On initial installation of Windows Script Host, the default script host is WScript. To change it to CScript, type the following at a command line. (On computers running Windows Vista, open the command prompt by using Run as administrator.)

cscript //h:cscript

To change the default host from CScript to WScript, type the following at a command line.

cscript //h:wscript

Sleep

WScript.Sleep 100

Subroutines

Sub CheckError
  ...
End Sub

Functions

Sub Sort( ByRef myArray )
End Sub
Sub Sort( ByVal myArray )
End Sub

Arrays

Display array on screen:

WScript.Echo Join( myArray, vbCrLf )

input box

inputBox Prompt, Title, Default, Xpos, Ypos, HelpFile, Context
inputbox "hello", "title", "default text"

message box

MsgBox Prompt, Buttons, Title
MsgBox "Please run this script with cscript.exe." & Chr(13) & _
  "For example : cscript " & WScript.ScriptName & " /?", _ 
  vbExclamation, WScript.ScriptName

Buttons:

CONSTANT VALUE DESCRIPTION
VBOKOnly 0 Show OK button
VBOKCancel 1 Show OK and cancel buttons
VBAbortRetryIgnore 2 Show abort, retry, ignore buttons
VBYesNoCancel 3 Show yes, no cancel buttons
VBYesNo 4 Show yes, no buttons
VBRetryCancel 5 Show retry, cancel buttons
VBCritical 16 Show critical message icon
VBQuestion 32 Show warning query button
VBExclamation 48 Show warning message icon
VBInformation 64 Show information message icon
VBDefaultButton1 0 First button is default
VBDefaultButton2 256 Second button is default
VBDefaultButton3 512 Third button is default
VBDefaultButton4 768 Fourth button is default
VBApplicationModal 0 Demands that the user respond to the dialog before allowing continuation of work in current application
VBSystemModal 4096 Causes suspension of all applications until the user responds to the dialog


Return Values:

CONSTANT VALUE BUTTON
VBOK 1 OK
VBCancel 2 Cancel
VBAbort 3 Abort
VBRetry 4 Retry
VBIgnore 5 Ignore
VBYes 6 Yes
VBNo 7 No

Command Line Parameters

Script name:

wscript.scriptname

Arguments:

Set Args = Wscript.Arguments
If Args.Count = 0 Then
  ...
End If
strArg1 = Args(0)
Set args = WScript.Arguments
FirstArg = args.Item(0)
SecondArg = args.Item(0)

References:

Error Handling

'** Add Error Handling
on error resume Next
...
If err.number = vbEmpty Then
  ...
 End If


'** Make sure the script is started with cscript
If InStr(wscript.FullName, "wscript.exe") > 0 Then
  MsgBox "Please run this script with cscript.exe." & Chr(13) & _
    "For example : cscript " & WScript.ScriptName & " /?", _ 
    vbExclamation, WScript.ScriptName
  WScript.Quit(1)
End If

True Random Numbers

"Computer generated random numbers are not true random numbers. They are retrieved from a stored semi-random sequence. That is why websites like random.org and random.irb.hr exist. They use atmospherical noise and photonic emission in semiconductors respectively, which is more truly random than anything that computer software can generate." [3]

Environment Variables

Set wshShell = CreateObject( "WScript.Shell" )
WScript.Echo wshShell.ExpandEnvironmentStrings( "%PATHEXT%" )
wshShell = Nothing

Dates

TYear = Year(Date)
' 2011
TMonth = Month(Date)
' 3
TDay = Day(Date)
' 7
Today = TYear & "-" & TMonth & "-" & TDay

Include

set oFile = fso.OpenTextFile(sFileName,1)
sText = oFile.ReadAll
oFile.close
ExecuteGlobal sText 

Source: [4]


You can create a (relatively) small function in each file that you want to include other files into, as follows: [5]

sub includeFile (fSpec)
    dim fileSys, file, fileData
    set fileSys = createObject ("Scripting.FileSystemObject")
    set file = fileSys.openTextFile (fSpec)
    fileData = file.readAll ()
    file.close
    executeGlobal fileData
    set file = nothing
    set fileSys = nothing
end sub
includeFile "commonapi.vbi"
includeFile "dbcalls.vbi"

Examples

randomize.vbs

intHighNumber = 100
intLowNumber = 1

For i = 1 to 5
    Randomize
    intNumber = Int((intHighNumber - intLowNumber + 1) * Rnd + intLowNumber)
    wscript.echo Int(rnd)
    Wscript.Echo intNumber
Next

Self-Destruct

' Author:   Denis St-Pierre
' Function: Make a script delete itself
Set objFSO = CreateObject( "Scripting.FileSystemObject" )
objFSO.DeleteFile WScript.ScriptFullName
WScript.Quit 

defrag.vbs

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'Dfrgntfs.exe'")

If colProcesses.Count = 0 Then
    Wscript.Echo " Dfrgntfs.exe is not running."
Else
    Wscript.Echo " Dfrgntfs.exe is running."
End If

vnc.vbs

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'winvnc.exe'")

If colProcesses.Count = 0 Then
    Wscript.Echo " winvnc.exe is not running."
Else
    Wscript.Echo " winvnc.exe is running."
End If

ADS - role.vbs

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colComputers = objWMIService.ExecQuery _
    ("Select DomainRole from Win32_ComputerSystem")

For Each objComputer in colComputers
    Select Case objComputer.DomainRole 
        Case 0 
            strComputerRole = "Standalone Workstation"
        Case 1        
            strComputerRole = "Member Workstation"
        Case 2
            strComputerRole = "Standalone Server"
        Case 3
            strComputerRole = "Member Server"
        Case 4
            strComputerRole = "Backup Domain Controller"
        Case 5
            strComputerRole = "Primary Domain Controller"
    End Select
    Wscript.Echo strComputerRole
Next

ADS - listaccounts.vbs

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = _
    "Select Name, Location from 'LDAP://DC=ut,DC=keylabs,DC=com' " _
        & "Where objectClass='computer'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    Wscript.Echo "Computer Name: " & objRecordSet.Fields("Name").Value
    Wscript.Echo "Location: " & objRecordSet.Fields("Location").Value
    objRecordSet.MoveNext
Loop

mysqltest.vbs

'******************************************************************************************
'Script Name: mysqltest.vbs 
'Author: Martin Lydon
'Created: 26/06/2006
'Description: First attempt at MySQL Connection using local DSN - MySQL 3.51 ODBC Connector
'******************************************************************************************
'Script Initialisation

OPTION EXPLICIT
Dim objDB,arrRecord,strRecord,strOutput
Dim oRS, nRec, oFld

'Main Processing section
'Database connection & select all from Table
Set objDB = DBConnect()
Set oRS = objDB.Execute("SELECT * FROM martin LIMIT 3")
'Dump Records from Table
WScript.Echo "Recordset Dump:"
nRec = 0
Do While Not oRS.EOF
  WScript.Echo "-----", nRec : nRec = nRec + 1
  For Each oFld In oRS.Fields
      WScript.Echo oFld.Name & " = " & oFld.Value
  Next
  oRS.MoveNext
Loop

'Procedures section
'This function sets up DB Connection using specified DSN
  Function DBConnect
  Set objDB = CreateObject("ADODB.Connection")
  objDB.Open "portal"
  Set DBConnect = objDB
End Function

write all your data to a textfile

    ' Set up Constants
    Const ForWriting = 2 ' Input OutPut mode
    Const Create = True
   
    Dim MyFile
    Dim FSO ' FileSystemObject
    Dim TSO ' TextStreamObject
   
    ' Use MapPath function to get the Physical Path of file
   
    MyFile = Server.MapPath("textfile.txt")
   
    Set FSO = Server.CreateObject("Scripting.FileSystemObject")
    Set TSO = FSO.OpenTextFile(MyFile, ForWriting, Create)
   
    TSO.Write "This is first line in this text File" & vbCrLf
    ' Vbcrlf is next line character
    TSO.Write "This is Second line in this text file" & vbCrLf
    TSO.Write "Writen by devasp visitor at " & Now()
    TSO.WriteLine ""
   
    Response.Write " Three lines are writen to textfile.txt <br>"
    Response.Write " Local time at server is " & Now()
   
    ' close TextStreamObject and
    ' destroy local variables to relase memory
    TSO.Close
    Set TSO = Nothing
    Set FSO = Nothing

stdout and stdin


Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Do While Not StdIn.AtEndOfStream
     str = StdIn.ReadLine
     StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop

Work with the Registry

' Create a WSH Shell object:
Set wshShell = CreateObject( "WScript.Shell" )
'
' Create a new key:
wshShell.RegWrite "HKCU\TestKey\", ""

' Create a new DWORD value:
wshShell.RegWrite "HKCU\TestKey\DWordTestValue", 1, "REG_DWORD"

' Create a new subkey and a string value in that new subkey:
wshShell.RegWrite "HKCU\TestKey\SubKey\StringTestValue", "Test", "REG_SZ"

' Read the values we just created:
WScript.Echo "HKCU\TestKey\DWordTestValue = " _
           & wshShell.RegRead( "HKCU\TestKey\DWordTestValue" )
WScript.Echo "HKCU\TestKey\SubKey\StringTestValue = """ _
           & wshShell.RegRead( "HKCU\TestKey\SubKey\StringTestValue" ) & """"

' Delete the subkey and key and the values they contain:
wshShell.RegDelete "HKCU\TestKey\SubKey\"
wshShell.RegDelete "HKCU\TestKey\"

' Note: Since the WSH Shell has no Enumeration functionality, you cannot
'       use the WSH Shell object to delete an entire "tree" unless you
'       know the exact name of every subkey.
'       If you don't, use the WMI StdRegProv instead.

' Release the object
Set wshShell = Nothing

ASP.NET VBScript

See ASP.NET VBScript

IDE

VBScript IDE + Debugger:

has anyone come across and VBScript IDE with integrated debugging? It should have all the usual features
I'd expect from an IDE such as syntax highlighting and completion plus integrated debugging with single
step and variable inspection.
No recommendations on this myself but you've encouraged me to go looking so here's what I've found so far:

http://www.primalscript.com/Editions...onal/index.asp

This one looks promising (ie: cheaper and easier to use)
http://www.vbsedit.com/

... and another for good luck
http://www.script-debugger.com/produ...r/debugwsh.asp

I think I'll take a crack at vbsedit first when I get a chance but hopefully this is a start.
@Geoff: Doesn't the Express edition of VisualBasic do this?
I've used PrimalScript and it is very good.

Must say that I prefer scripting in AutoIT these days. One of the reasons I love it is that wherever I am, I can download the whole thing (interpreter, compiler, help file and IDE) in a few seconds from the web site. It compiles to .EXE and comes with a far richer set of commands than VBS. Then there is the whole GUI thing if you need it, not to mention all the extra user defined functions, windows automation, COM functionality...

I've yet to discover anything that you can do in VBS that you can't in AutoIT. The reverse, however, is far from true!


VBScript Editor / IDE:

I think Textpad would work.
www.textpad.com 
vbsedit - it has setp/debug which is good and loads of built in code samples

VbsEdit costs $49


One of the above sites:

Microsoft Visual Web Developer 2005 works a treat for vbscript. The intellisense works even with vbscript, and it has a full knowledge of the DOM allowing for Autocomplete in client side scripting.  
<pre>

[http://xtremeworlds.com/forums/viewtopic.php?f=5&t=2101 Xtreme Worlds • View topic - FREE VBScript IDE]:
<pre>
I found a free VBScript IDE. Actually, it's a universal IDE, and it works very well:

http://www.pspad.com/en/

(Not completely in English)

An alternate to PsPad that is entirely English, but not a true IDE:

http://notepad-plus.sourceforge.net/uk/site.htm

(Not fully featured)

I have also found a debugger with a free trial:

http://www.softpedia.com/get/Internet/W ... -IDE.shtml

(Not free)

I have Cross-Checked ALL sites for legitimacy and Virus-Scanned their downloads.


PSPad forum / English discussion forum / QUERY: PSPad VBScript debugger/executor

Is it possible to execute/debug VBScripts in PSPad? Like a VBScript editor & debugger?
You can excute and catch output of the script if you use command line script interpreter.
Program settings / VBScript / Compiler tab
With Ctrl+F9 you run your script
This worked for me to execute scripts.

Save a simple .vbs file, e.g.,

Dim i
For i = 1 to 10
WScript.Echo "Hello World"
Next
MsgBox "Check your log", vbInformation

Under Settings > Highlighters Settings > MS VBscript > Compilers tab:

Compiler: C:\WINDOWS\system32\cscript.exe
Parameters: "%File%"

Optional (experiment and see what you like):
LOG File:
[x] Capture program output window


Real Life Forums • View topic - VBScript IDE?

I need a good IDE for editing VBScript. No, it's not for websites. A program we use at work utilized JScript and VBScript for its scripting capabilities. (Coming versions of the program will allow for Perl, Python, and REXX, and I'm pushing them to include PHP, though I'll script in REXX if I can't do PHP just to annoy others at work.)
Anyway, VBScript has better array controls than does JScript, but the IDEs out there are lacking. Does anyone have suggestions for something that's free (it takes months to get a purchasing request through the system)? Ideally, I'd like something like PHPEdit, with context-sensitive help and autocomplete, but it's not really required. Syntax coloring is necessary, though, because of the volume of the work I do (one script is already approaching 20KB, and will likely exceed 30KB before I'm done).
Note: VIM and emacs are out. I need something without a learning curve that requires a rocket jump to get past, because the script development is moving forward so quickly.


http://sourceforge.net/projects/aspprofiler/
Development Status: 5 - Production/Stable

    A line-level performance profiler for ASP (VBScript) code. Optimize ASP by seeing how many times each line was executed and how long it took. Written in pure ASP, it supports nested server-side includes, and features a client-side sorting dynamic table. 



--

http://sourceforge.net/projects/tclscript/
Development Status: 2 - Pre-Alpha

    The TclScript project will provide the Tcl language as an Active Scripting COM object for use under Microsoft Windows. This will allow Tcl to be used anywhere where either VBScript or JScript is currently used by Windows applications. As a sideline, this 



--

http://sourceforge.net/projects/bsfasp/
This Project Has Not Released Any Files

    BSF ASP is a implementation of ASP as a java servlet with scripting language support provided by the Bean Scripting Framework so that pages can be created in a number of program languages including VBScript, JavaScript, Python, NetRex, etc. 



--

http://sourceforge.net/projects/pgiacd/
Development Status: 1 - Planning, 2 - Pre-Alpha

    The PGIA CD, is an informational educational and (hopefully) well designed Development Environment Suite. The Development Suite, natively supports C,C++,C#,VBScript,Assembly,Visual Basic,Visual Basic .NET and Pascal. Alongside it is the customising script 




That's what comes up when searching for
vbscript ide
and having the checkbox for require all words.

I included other info because I could. Because of how you're going to use it, it seems ASPProfiler would be best, it's also stable. 
http://www.google.com/search?q=VBScript+IDE 
jEdit is OSS and supports a VBScript edit mode. (Which basically gives you syntax highlighting and in theory will help with indentation when it comes to IF statements and the like.)

Unfortunately, it requires Java, so it may not be an option. I use it for editting JSPs and PHPs all the time and rather like it. But it's not really an IDE. (Although there are some plugins to try and make it into a Java IDE. They don't really succeed.)

I doubt you're going to find what you're looking for Martin, but good luck anyway. The only VBScript IDE I've ever used was Visual Studio, and I doubt that's the answer you're looking for. :)