{ WSH VBScript REFERENCE }

Similar documents
Understanding the MsgBox command in Visual Basic

variables programming statements

Programming Concepts and Skills. Arrays continued and Functions

Excel & Visual Basic for Applications (VBA)

An InputBox( ) function will display an input Box window where the user can enter a value or a text. The format is

VB Script Examples. This document contains only examples. It is a live document, and is continuously being updated. Last update: March 27, 2017

MICROSOFT EXCEL 2000 LEVEL 5 VBA PROGRAMMING INTRODUCTION

As an A+ Certified Professional, you will want to use the full range of

How to detect the CPU and OS Architecture

4 Working with WSH objects

6/14/2010. VBA program units: Subroutines and Functions. Functions: Examples: Examples:

Creating Macros David Giusto, Technical Services Specialist, Synergy Resources

IFA/QFN VBA Tutorial Notes prepared by Keith Wong

'Attribute_value = objarguments(0) 'String representing the secedit attribute to test

Overview. Program Start VB SCRIPT SIGNER. IT Services

Visual Programming 1. What is Visual Basic? 2. What are different Editions available in VB? 3. List the various features of VB

3 IN THIS CHAPTER. Understanding Program Variables

Using VBScript For Perfecting Statistical Report

MICROSOFT EXCEL VISUAL BASIC FOR APPLICATIONS INTERMEDIATE

Chapter 14 Sequential Files

The Item_Master_addin.xlam is an Excel add-in file used to provide additional features to assist during plan development.

Excel Macro Record and VBA Editor. Presented by Wayne Wilmeth

KEYWORDS DDE GETOBJECT PATHNAME CLASS VB EDITOR WITHEVENTS HMI 1.0 TYPE LIBRARY HMI.TAG

Windows Batch file to Easily Convert MagicLantern.RAW files into CinemaDNG Posted by idealsceneprod - 09 Nov :17

Disables all services configured as manual start. Among other things, this prevents Power Users from being able to start these services.

How to save money on Oracle Java Client Licenses

'... '... '... Module created: unknown '... Proj finished: March 21, 2012 '... '...

VBA. VBA at a glance. Lecture 61

00:33 Network Loses Connection. 00:30 Health Check. Sweep all files in the monitored folder regardless of when deposited (i.e., process ALL files).

Programming with visual Basic:

Chapter 1. Block Diagram. Text .. 1

DIGIBRANDING SIGNATURE SCRIPT Stepped Out

Excel VBA Programming

Associating Run As Accounts in Operations Manager 2007

IFA/QFN VBA Tutorial Notes prepared by Keith Wong

Microsoft System Center Configuration Manager Dell Factory Integration

Retrieve the shortcut properties from all the shortcuts in the Start Menu

BASIC EXCEL SYLLABUS Section 1: Getting Started Section 2: Working with Worksheet Section 3: Administration Section 4: Data Handling & Manipulation

Script Host 2.0 Developer's Guide

PrimalScript. Your First 20 Minutes. Your First 20 Minutes. Start here to be productive with PrimalScript in just 20 minutes.

MonitorPack Guard deployment

TIPS & TRICKS SERIES

Microsoft Excel Level 2

I

Microsoft System Center Configuration Manager 2012 Dell Factory Integration

INFORMATICS: Computer Hardware and Programming in Visual Basic 81

ZENworks 11 Support Pack 4 Endpoint Security Scripting Reference. October 2016

ZENworks 2017 Endpoint Security Scripting Reference. December 2016

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Respond to Data Entry Events

Compact Disc 1. Send us your feedback «Previous Next» Microsoft Windows 2000 Scripting Guide

ENGG1811 Computing for Engineers Week 9 Dialogues and Forms Numerical Integration

Download the files from you will use these files to finish the following exercises.

Smart Access. CROSSTAB queries are helpful tools for displaying data in a tabular. Automated Excel Pivot Reports from Access. Mark Davis. vb123.

VBA Collections A Group of Similar Objects that Share Common Properties, Methods and

#44. Accelerate Skype Using Your Keyboard Make Skype fly, by speeding up common tasks with key sequences and hotkeys.

Accessing Password Protected Microsoft Excel Files in A SAS Grid Environment

Putting It All Together: Your First WMI/ADSI Script

Putting It All Together: Your First WMI/ADSI Script

MgtOp 470 Business Modeling with Spreadsheets Sample Midterm Exam. 1. Spreadsheets are known as the of business analysis.

A Back-End Link Checker for Your Access Database

PROGRAMATICALLY STARTING AND STOPPING AN SAP XMII UDS EXECUTABLE INSTANCE

The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.

Microsoft Excel > Shortcut Keys > Shortcuts

Lookup Project. frmlookup (Name: object is a combo box, style 2); use 4 labels: 2 for phone, 2 for mail. MsgBox Function:

Microsoft Excel 2016 Level 1

MICROSOFT EXCEL KEYBOARD SHORCUTS

Microsoft Excel 2010 Level 1

Tools for the VBA User

The name of this chapter is Dealing with Devices, but of

Dell OpenManage Essentials v1.1 Supporting Dell Client Devices

Introduction to Computer Use II

BASIC MACROINSTRUCTIONS (MACROS)

The WebBrowser control is the heart of Internet Explorer. It can. Using the WebBrowser Control. Chapter 19

3. (1.0 point) To quickly switch to the Visual Basic Editor, press on your keyboard. a. Esc + F1 b. Ctrl + F7 c. Alt + F11 d.

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

'Get the old path from the registry value we write using this script stroldpath = GetOldPath()

1) Identify the recording mode, by which you can record the non-standard object in QTP

WinINSTALL 9.0 Master Document to be used as an internal resource only

d2vbaref.doc Page 1 of 22 05/11/02 14:21

Dell OpenManage Essentials v2.0 Support for Dell Client Devices

Lesson 2. Using the Macro Recorder

Microsoft Excel 2013 Unit 1: Spreadsheet Basics & Navigation Student Packet


Autodesk Inventor Tutorials by Sean Dotson VBA Functions in Parts Part Two Latest Revision: 3/17/03 For R Sean

Excel Macro Runtime Error Code 1004 Saveas Of Object _workbook Failed

MS Excel VBA Class Goals

How to modify convert task to use variable value from source file in output file name

Getting started 7. Writing macros 23

Outline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014

Table of Contents Data Validation... 2 Data Validation Dialog Box... 3 INDIRECT function... 3 Cumulative List of Keyboards Throughout Class:...

Advanced Excel. Click Computer if required, then click Browse.

Debugging Runtime Scripts in Operations Manager and Essentials 2007 The third installment in the System Center Forum Scripting Series

Excel Template Instructions for the Glo-Brite Payroll Project (Using Excel 2010 or 2013)

IT ACADEMY LESSON PLAN

Study Guide. PCIC 3 B2 GS3- Key Applications-Excel. Copyright 2010 Teknimedia Corporation

Day : Date : Objects : Open MS Excel program. Subject : * Open Excel application. Select : start. Choose: programs. Choose : Microsoft Office

KEYBOARD SHORTCUTS AND HOT KEYS

I OFFICE TAB... 1 RIBBONS & GROUPS... 2 OTHER SCREEN PARTS... 4 APPLICATION SPECIFICATIONS... 5 THE BASICS...

Ms Excel Vba Continue Loop Through Range Of

Transcription:

{ WSH VBScript REFERENCE } WSH Template <Tags Required to Run> <job id="01"> <script language="(vbscript JScript ">..code goes here </script> </job> SUBS No Return Value Sub mysub() some statements Sub mysub(argument1,argument2) some statements FUNCTIONS Return Value <package> <job id="j1"> <?job debug="false" error="false"?> <script language="jscript" src="zgh.js" /> <script language="vbscript"> s = GetFreeSpace("c:") WScript.Echo s </script> </job> <job id="j2"> <?job debug="false" error="false"?> <script language="vbscript" src="zgh.vbs" /> <script language="vbscript"> s = ReportFileStatus("C:\zgh.js") WScript.Echo s </script> </job> </package> Function myfunction(argument1,argument2) some statements myfunction=some value End Function IF ELSE CONDITIONS if i=10 Then msgbox "Hello" i = i+1 end If if i=10 then msgbox "Hello" else msgbox "Goodbye" end If <job id="01"> <script language="vbscript"> Dim oshell Set oshell = WScript.CreateObject("WScript.shell") 'oshell.run "C:\WINNT\explorer" 'WScript.Sleep 3000 oshell.run """C:\Program Files\Microsoft Office\Office10\FRONTPG.EXE"" C:\Inetpub\wwwroot\pvtGH" WScript.Sleep 14000 oshell.run """c:\program Files\Internet Explorer\IEXPLORE.EXE"" http://www.google.com/" WScript.Sleep 3000 Set oshell = Nothing </script> </job> if payment="cash" then msgbox "You are going to pay cash!" elseif payment="visa" then msgbox "You are going to pay with visa." elseif payment="amex" then msgbox "You are going to pay with American Express." else msgbox "Unknown method of payment." end If SELECT CASE CONDITIONAL BRANCHING select case payment case "Cash" msgbox "You are going to pay cash" case "Visa" msgbox "You are going to pay with visa" case "AmEx" msgbox "You are going to pay with American Express" case Else msgbox "Unknown method of payment" end select

FOR LOOPS For i=1 to 10 some code For i=2 To 10 Step 2 some code dim cars(2) cars(0)="volvo" cars(1)="saab" For Each x in cars document.write(x & "<br />") 0 = vbapplicationmodal - Application modal (the current application will not work until the user responds to the message box) 4096 = vbsystemmodal - System modal (all applications wont work until the user responds to the message box) CREATE OBJECTS Using VbScript to Create Objects Dim adoapp As Object adoapp = CreateObject("ADODB.Connection") Dim xlapp As Object xlapp = CreateObject("Excel.Application", "\\MyServer") Set objfso = CreateObject("Scripting.FileSystemObject") Set objfso = Wscript.CreateObject("Scripting.FileSystemObject") Using wscript to create objects DO WHILE LOOPS Do Until i=10 some code Loop Do some code Loop Until i=10 Do Until i=10 i=i-1 If i<10 Then Exit Do Loop MSGBOX Dim answer answer=msgbox("hello everyone!",65,"example") document.write(answer) 1 = vbok - OK was clicked 2 = vbcancel - Cancel was clicked 3 = vbabort - Abort was clicked 4 = vbretry - Retry was clicked 5 = vbignore - Ignore was clicked 6 = vbyes - Yes was clicked 7 = vbno - No was clicked 0 = vbokonly - OK button only 1 = vbokcancel - OK and Cancel buttons 2 = vbabortretryignore - Abort, Retry, and Ignore buttons 3 = vbyesnocancel - Yes, No, and Cancel buttons 4 = vbyesno - Yes and No buttons 5 = vbretrycancel - Retry and Cancel buttons 16 = vbcritical - Critical Message icon 32 = vbquestion - Warning Query icon 48 = vbexclamation - Warning Message icon 64 = vbinformation - Information Message icon 0 = vbdefaultbutton1 - First button is default 256 = vbdefaultbutton2 - Second button is default 512 = vbdefaultbutton3 - Third button is default 768 = vbdefaultbutton4 - Fourth button is default Set objreference = Wscript.CreateObject("Word.Application") Set objreference = Wscript.CreateObject("InternetExplorer.Application") Set objreference = Wscript.CreateObject("Scripting.Dictionary") Set objreference = Wscript.CreateObject("Wscript.Network") The first line uses VBScript, and the second uses WSH: Set objexcel = CreateObject("Excel.Application", "Parameter2") Set objexcel = Wscript.CreateObject("Excel.Application", "Parameter2") GET OBJECTS Set objword = WScript.GetObject("C:\test.doc") objword.application.visible = True WScript.Echo "You just opened", objword.name Set objwmiservice = GetObject ("winmgmts:\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery ("SELECT * FROM WIN32_OperatingSystem") For Each objitem in colitems Wscript.Echo objitem.caption OUTPUT Set objnetwork = Wscript.CreateObject("Wscript.Network") Set objstdout = WScript.StdOut objstdout.write "User: " objstdout.write objnetwork.userdomain objstdout.write "\" objstdout.write objnetwork.username objstdout.writeblanklines(1) objstdout.writeline objnetwork.computername objstdout.close

{ FILESYSTEM OBJECT } FileSystem Objects Creation Dim fso Dim FSO Set fso = CreateObject("Scripting.FileSystemObject") Set FSO = CreateObject("Scripting.FileSystemObject") Copy File FSO.CopyFile "c:\compluslog.txt", "c:\x\" Copy Folder FSO.CopyFolder "c:\folder_x", "c:\folder_y" or FileSystemObject.CopyFolder "c:\mydocuments\letters\*", "c:\tempfolder\" Move Folder fso.movefolder Drivespec, "c:\windows\desktop\" Get Special Folders Use for Temp, System and Windows Folder WindowsFolder - 0 SystemFolder - 1 Temp - 2 var tfolder, tfile, tname, fname, TemporaryFolder = 2; tfolder = fso.getspecialfolder(temporaryfolder); WSH SLEEP METHOD Wscript.Sleep 300000 WSH TIMEOUT Wscript.Timeout = 5 WSH QUIT Wscript.Quit Get File Set f = fso.getfile(filespec) Get FileName GetAName = fso.getfilename(drivespec) Get Folder Set f = fso.getfolder(path) Create a Text File Set MyFile = fso.createtextfile("c:\testfile.txt", True) Create a Folder Set f = fso.createfolder("c:\new Folder") Open Text File Set f = fso.opentextfile("c:\testfile.txt", ForWriting, True) ForReading ForWriting ForAppending Delete File fso.deletefile(filespec) WSHSHELL SENDKEYS Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "notepad", 9 WScript.Sleep 500 ' Give Notepad some time to load For i = 1 To 10 WshShell.SendKeys "Hello World!" WshShell.SendKeys "{ENTER}" BACKSPACE {BACKSPACE}, {BS}, or {BKSP} DEL or DELETE {DELETE} or {DEL} ENTER {ENTER} or ~ PRINT SCREEN {PRTSC} TAB {TAB} F1 F12 {F1}-{Fn} SHIFT + CTRL ^ ALT % For example, the following strkeystring produces the CTRL-ALT-DELETE keystroke combination: "^%{DELETE}" Delete Folder fso.deletefolder(filespec) File Exist Check If (fso.fileexists(filespec)) Then msg = filespec & " exists." Else msg = filespec & " doesn't exist." SETTING UP NETWORK SHARES Set WshNetwork = WScript.CreateObject("WScript.Network") WshNetwork.MapNetworkDrive "Z:", "\\Server\PublicFiles" WshNetwork.RemoveNetworkDrive "Z:" Set WshNetwork = WScript.CreateObject("WScript.Network") WshNetwork.MapNetworkDrive "Z:", "\\Server\PublicFiles" WshNetwork.RemoveNetworkDrive "Z:" If Folder Exists If (fso.folderexists(fldr)) Then msg = fldr & " exists." Else msg = fldr & " doesn't exist."

LOGGING EVENTS Set WshShell = CreateObject("WScript.Shell") WshShell.LogEvent 4, "Script started." WshShell.LogEvent 0, "Script completed." 0 SUCCESS 1 ERROR 2 WARNING 4 INFORMATION 8 AUDIT_SUCCESS 16 AUDIT_FAILURE RUNNING SCRIPTS WScript.Echo msg HOST RESOURCES Set objconnection = GetObject("WinNT://atl-ws-01/LanmanServer") Set colresources = objconnection.resources For Each objresource in colresources Wscript.Echo "Path: " & objresource.path Wscript.Echo "User: " & objresource.user Wscript.Echo > cscript //nologo c:\"sample scripts"\chart.vbs > cscript myscript.wsf. INPUTBOX stranswer = InputBox("Please enter a name for your new file:", _ "Create File") If stranswer = "" Then Wscript.Quit Else Wscript.Echo stranswer Set objwmiservice = GetObject _ ("winmgmts:\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery _ ("SELECT * FROM WIN32_OperatingSystem") For Each objitem in colitems Wscript.Echo objitem.caption DATES and DATE TIME dtmtoday = Date() dtmdayofweek = DatePart("w", dtmtoday) SETTING UP ARGUMENTS IN COMMAND LINE Example: Set args = WScript.Arguments num = args.count If num = 0 then WScript.Echo "Usage: [CScript WScript] drivespace.vbs <driveletters>" WScript.Quit 1 End if Set FileSystemObj = CreateObject("Scripting.FileSystemObject") msg = "Drive space report" & vbcrlf For k = 0 To num - 1 driveletter = args.item(k) Set drive = FileSystemObj.GetDrive(DriveLetter) FindSpace drive, msg

WSH TEXT STREAM OBJECT: TextStream A Textstream object is returned by the StdErr, StdIn and StdOut properties of the WScript object. For full details of this object and its properties and methods, see the VBScript Textstream object Quick Reference. TEXT STREAM PROPERTIES AtEndOfLine Property Returns a Boolean value. If the file pointer is positioned immediately before the file's end-of-line marker, the value is True, and False otherwise. Syntax: object.atendofline AtEndOfStream Property Returns a Boolean value. If the file pointer is positioned at the end of a file, the value is True, and False otherwise. Syntax: object.atendofstream Column Property Returns the current position of the file pointer within the current line. Column 1 is the first character in each line. Moves the file pointer from its current position to the beginning of the next line. Syntax: object.skipline Write Method This method writes the parameter string to an open TextStream file. Syntax: object.write(string) WriteLine Method Writes the optional parameter string to a TextStream file, followed by a new line character. Syntax: object.writeline([string]) WriteBlankLines Method Used to write a number of consecutive newline characters (defined with the lines parameter) to a TextStream file. Syntax: object. WriteBlankLines (lines) Syntax: object.column Line Property This property returns the current line number in a text file. Syntax: object.line TEXT STREAM METHODS Close Method Closes a currently open TextStream file. Syntax: object.close Read Method This method reads the number of characters you specify from a Textstream file and returns them as a string. Syntax: object.read(characters) ReadAll Method This method reads the entire contents of a text file and returns it as a string. Syntax: object.readall ReadLine Method Reads a single line (excluding the newline character) from a TextStream file and returns the contents as a string. Syntax: object.readline Skip Method Causes the file pointer to skip a specified number of characters when reading a TextStream file. Can be a positive or negative number. Syntax: object.skip(characters) SkipLine Method

VBScript - EXCEL & WORD objexcel.visible = True objexcel.workbooks.add objexcel.cells(1, 1).Value = "Test value" OPEN a Spreadsheet Set objworkbook = objexcel.workbooks.open("c:\scripts\new_users.xls") READ an Excel Spreadsheet Set objworkbook = objexcel.workbooks.open _ ("C:\Scripts\New_users.xls") introw = 2 Do Until objexcel.cells(introw,1).value = "" Wscript.Echo "CN: " & objexcel.cells(introw, 1).Value Wscript.Echo "samaccountname: " & objexcel.cells(introw, 2).Value Wscript.Echo "GivenName: " & objexcel.cells(introw, 3).Value Wscript.Echo "LastName: " & objexcel.cells(introw, 4).Value introw = introw + 1 Loop objexcel.quit Get User Based Accounts on Excel Info Set objworkbook = objexcel.workbooks.open _ ("C:\Scripts\New_users.xls") introw = 2 Do Until objexcel.cells(introw,1).value = "" Set objou = GetObject("ou=Finance, dc=fabrikam, dc=com") Set objuser = objou.create _ ("User", "cn=" & objexcel.cells(introw, 1).Value) objuser.samaccountname = objexcel.cells(introw, 2).Value objuser.givenname = objexcel.cells(introw, 3).Value objuser.sn = objexcel.cells(introw, 4).Value objuser.accountdisabled = FALSE objuser.setinfo introw = introw + 1 Loop objexcel.quit Format A Range of Cells GET Active Row and Used Range of Cells Const xlcelltypelastcell = 11 objexcel.visible = True Set objworkbook = objexcel.workbooks.open("c:\scripts\test.xls") Set objworksheet = objworkbook.worksheets(1) objworksheet.activate Set objrange = objworksheet.usedrange objrange.specialcells(xlcelltypelastcell).activate intnewrow = objexcel.activecell.row + 1 strnewcell = "A" & intnewrow objexcel.range(strnewcell).activate ADD Format Data to Spreadsheet objexcel.visible = True objexcel.workbooks.add objexcel.cells(1, 1).Value = "Test value" objexcel.cells(1, 1).Font.Bold = TRUE objexcel.cells(1, 1).Font.Size = 24 objexcel.cells(1, 1).Font.ColorIndex = 3 Add Data To Worksheet objexcel.visible = True objexcel.workbooks.add objexcel.cells(1, 1).Value = "Name" objexcel.cells(1, 1).Font.Bold = TRUE objexcel.cells(1, 1).Interior.ColorIndex = 30 objexcel.cells(1, 1).Font.ColorIndex = 2 objexcel.cells(2, 1).Value = "Test value 1" objexcel.cells(3, 1).Value = "Test value 2" objexcel.cells(4, 1).Value = "Tets value 3" objexcel.cells(5, 1).Value = "Test value 4" Set objrange = objexcel.range("a1","a5") objrange.font.size = 14 Set objrange = objexcel.range("a2","a5") objrange.interior.colorindex = 36 Set objrange = objexcel.activecell.entirecolumn objrange.autofit() List Service Data in Excel objexcel.visible = True objexcel.workbooks.add x = 1 strcomputer = "." Set objwmiservice = GetObject _ ("winmgmts:\\" & strcomputer & "\root\cimv2") Set colservices = objwmiservice.execquery _ ("Select * From Win32_Service")

For Each objservice in colservices objexcel.cells(x, 1) = objservice.name objexcel.cells(x, 2) = objservice.state x = x + 1 AUTO RUN Excel Macro Sub auto1() Dim objxl As Object, x On Error Resume Set objxl = CreateObject("Excel.Application") With objxl.application.visible = True 'Open the Workbook.Workbooks.Open "C:\Documents and Settings\admin\Desktop\TEST\test.xlsx" 'Include CARMA in menu, run AutoOpen.ActiveWorkbook.RunAutoMacros xlautoopen x =.Run("AccountsViewEngine", 0) End With Set objxl = Nothing EXCEL EXAMPLE Dim objxl Set objxl = WScript.CreateObject("Excel.Application") objxl.visible = TRUE objxl.workbooks.add objxl.columns(1).columnwidth = 20 objxl.columns(2).columnwidth = 30 objxl.columns(3).columnwidth = 40 objxl.cells(1, 1).Value = "Property Name" objxl.cells(1, 2).Value = "Value" objxl.cells(1, 3).Value = "Description" objxl.range("a1:c1").select objxl.selection.font.bold = True objxl.selection.interior.colorindex = 1 objxl.selection.interior.pattern = 1 'xlsolid objxl.selection.font.colorindex = 2 objxl.columns("b:b").select objxl.selection.horizontalalignment = &hffffefdd ' xlleft Dim intindex intindex = 2 Sub Show(strName, strvalue, strdesc) objxl.cells(intindex, 1).Value = strname objxl.cells(intindex, 2).Value = strvalue objxl.cells(intindex, 3).Value = strdesc intindex = intindex + 1 objxl.cells(intindex, 1).Select ' Show WScript properties Call Show("Name", WScript.Name, "Application Friendly Name") Call Show("Version", WScript.Version, "Application Version") Call Show("Path", WScript.Path, "Application Context: Path Only") Call Show("Interactive", WScript.Interactive, "State of Interactive Mode") ' Show command line arguments. ' Dim colargs Set colargs = WScript.Arguments Call Show("Arguments.Count", colargs.count, "Number of command line arguments") For i = 0 to colargs.count - 1 objxl.cells(intindex, 1).Value = "Arguments(" & i & ")" objxl.cells(intindex, 2).Value = colargs(i) intindex = intindex + 1 objxl.cells(intindex, 1).Select Sub Welcome() Dim intdoit intdoit = MsgBox(L_Welcome_MsgBox_Message_Text, _ vbokcancel + vbinformation, _ L_Welcome_MsgBox_Title_Text ) If intdoit = vbcancel Then WScript.Quit EXCEL EXAMPLE 2: Write To and Format Excel Option Explicit Dim objuser, strexcelpath, objexcel, objsheet, k, objgroup ' User object whose group membership will be documented in the ' spreadsheet. Set objuser = GetObject("LDAP://cn=User2,ou=Sales,dc=MyDomain,dc=com") ' Spreadsheet file to be created. strexcelpath = "c:\myfolder\usergroup.xls" ' Bind to Excel object. On Error Resume If (Err.Number <> 0) Then On Error GoTo 0 Wscript.Echo "Excel application not found." Wscript.Quit On Error GoTo 0 ' Create a new workbook. objexcel.workbooks.add ' Bind to worksheet. Set objsheet = objexcel.activeworkbook.worksheets(1) objsheet.name = "User Groups" ' Populate spreadsheet cells with user attributes. objsheet.cells(1, 1).Value = "User Common Name" objsheet.cells(2, 1).Value = "samaccountname" ' Enumerate groups and add group names to spreadsheet. k = 5

For Each objgroup In objuser.groups objsheet.cells(k, 2).Value = objgroup.samaccountname k = k + 1 ' Format the spreadsheet. objsheet.range("a1:a4").font.bold = True objsheet.select objsheet.range("b5").select objexcel.activewindow.freezepanes = True objexcel.columns(1).columnwidth = 20 objexcel.columns(2).columnwidth = 30 ' Save the spreadsheet and close the workbook. objexcel.activeworkbook.saveas strexcelpath objexcel.activeworkbook.close ' Quit Excel. objexcel.application.quit ' Clean Up Set objuser = Nothing Set objgroup = Nothing Set objsheet = Nothing Set objexcel = Nothing Wscript.Echo "Done" BASICS --New workbook Workbook Object: Workbooks(1).Activate Workbooks("Cogs.xls").Worksheets("Sheet1").Activate ActiveWorkbook.Colors = Workbooks("BOOK2.XLS").Colors Worksheets Object: Worksheets(1).Visible = False --setting Focus --Activate Method applies to: Chart, Worksheet, Pane, Window & Workbook Workbook("test.xlsx").Activate or ActiveWindow.Activate --Add fields method object.addfields(rowfields, ColumnFields, PageFields, AddToTable, AppendField) CopyCutMode Application.CutCopyMode = True False Not in Cut or Copy mode xlcopy In Copy mode xlcut In Cut mode Sub AddNew() Set NewBook = Workbooks.Add With NewBook.Title = "All Sales".Subject = "Sales".SaveAs Filename:="Allsales.xls" End With False True Cancels Cut or Copy mode and removes the moving border. Cancels Cut or Copy mode and removes the moving border. --Open a workbook Workbooks.Open("C:\MyFolder\MyBook.xls") Sub FirstOne() Worksheets(1).Activate To get data: a = Range("B2").Value or a = Cells(2,2).Value To set data: Range("C2").Value = r1 or Cells(3,2).Value = r1 Enter string data: Range("M2") = "Int. = " Cells(15,2) = "Int. = "

Const wdformattext = 2 objword.visible = TRUE Set objdoc = objword.documents.open("c:\scripts\mylog.doc") objdoc.saveas "c:\scripts\mylog.txt", wdformattext objword.quit Create a New Word Document Demonstration script that creates and displays a new Microsoft Word document. objword.visible = True Set objdoc = objword.documents.add() Open and Print a Word Document Set objdoc = objword.documents.open("c:\scripts\inventory.doc") objdoc.printout() objword.quit Using WSH in WORD Create and Save a Word Document Demonstration script that retrieves network adapter data from a computer, displays that data in a Microsoft Word document, and then saves the document as C:\Scripts\Word\Testdoc.doc. objword.caption = "Test Caption" objword.visible = True Set objdoc = objword.documents.add() Set objselection = objword.selection objselection.font.name = "Arial" objselection.font.size = "18" objselection.typetext "Network Adapter Report" objselection.font.size = "14" objselection.typetext "" & Date() objselection.font.size = "10" strcomputer = "." Set objwmiservice = GetObject("winmgmts:\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery _ ("Select * from Win32_NetworkAdapterConfiguration") objdoc.saveas("c:\scripts\word\testdoc.doc") objword.quit Add Formatted Text to a Word Document Demonstration script that displays formatted data in a Microsoft Word document. objword.visible = True Set objdoc = objword.documents.add() Set objselection = objword.selection objselection.font.name = "Arial" objselection.font.size = "18" objselection.typetext "Network Adapter Report" objselection.font.size = "14" objselection.typetext "" & Date() Add a Formatted Table to a Word Document objword.visible = True Set objdoc = objword.documents.add() Set objrange = objdoc.range() objdoc.tables.add objrange,1,3 Set objtable = objdoc.tables(1) x=1 strcomputer = "." Set objwmiservice = _ GetObject("winmgmts:\\" & strcomputer & "\root\cimv2") Set colitems = objwmiservice.execquery("select * from Win32_Service") For Each objitem in colitems If x > 1 Then objtable.rows.add() objtable.cell(x, 1).Range.Font.Bold = True objtable.cell(x, 1).Range.Text = objitem.name objtable.cell(x, 2).Range.text = objitem.displayname objtable.cell(x, 3).Range.text = objitem.state x = x + 1 Append Text to a Word Document Const END_OF_STORY = 6 Const MOVE_SELECTION = 0 objword.visible = True Set objdoc = objword.documents.open("c:\scripts\word\testdoc.doc") Set objselection = objword.selection objselection.endkey END_OF_STORY, MOVE_SELECTION objselection.font.size = "14" objselection.typetext "" & Date()

objselection.font.size = "10" DATABASE CONNECTION [odbcselect.vbs] Dim OdbcDSN Dim connect, sql, resultset OdbcDSN = "DSN=Sybase Demo DB V6 DWB;UID=dba;PWD=sql" Set connect = CreateObject("ADODB.Connection") connect.open OdbcDSN sql="select emp_fname, emp_lname FROM employee" Set resultset = connect.execute(sql) On Error Resume resultset.movefirst Do While Not resultset.eof WScript.Echo resultset("emp_lname") & ", " & resultset("emp_fname") resultset.move Loop resultset.close connect.close Set connect = Nothing WSCRIPT.QUIT(0) BASIS OF CONNECTION 'Create connection object set cn = Server.CreateObject("ADODB.Connection") cn = new ADODB.Connection 'Setting the DataSource strcs = "Driver={SQL Server}; Server=myserver; Database=mydb; UID=sa; PWD=password" Set cn = Server.CreateObject("ADODB.Connection") Set rs = Server.CreateObject("ADODB.Recordset") cn.connectionstring = Application("DB_CONN") cn.open end if ' Method to destroy objects created. Public Sub Destroy if isobject(rs) = true then rs.close Set rs = nothing end if if isobject(cn) = true then cn.close Set cn = nothing end if End Class NOW CALL IT Set db = new DataBaseFunction db.init Set db.rs = db.cn.execute("select * FROM tbluser WHERE UserID = 10") Response.Write(db.rs.Fields(1).value) db.destroy Set db = Nothing 'Setting the Connection String cn.connectionstring = strcs 'Open It cn.open USING A VBS CLASS TO CONNECT Class DataBaseFunctions ' Declare variables to have public scope. Public rs Public cn 'Method to initialize connection to database Private Sub Init if isobject(cn) = false then