I am really new to VBScript. So this is my code which reates a text file and attaches an object to it:
Set objExcel = CreateObject(\"Scripting.FileSystemO
VBScript GetObject documentation can be found here. Here is a VBScript sample:
Set objExcelFile = GetObject("C:\Scripts\Test.xls")
WScript.Echo objExcelFile.Name
objExcelFile.Close
This code will get you the Excel Workbook object contained in C:\Scripts\Test.xls. You can use TypeName() to confirm that:
Set objExcelFile = GetObject("C:\Scripts\Test.xls")
WScript.Echo objExcelFile.Name
WScript.Echo TypeName(objExcelFile)
objExcelFile.Close
The output will be:
test.xls
Workbook
If the specified Excel workbook doesn't exist the script will return an error. If an instance of Excel is already running you can use this code to get a reference to it:
Set objExcel = GetObject( , "Excel.Application")
For Each objWorkbook In objExcel.Workbooks
WScript.Echo objWorkbook.Name
Next
objExcel.Quit
Notice the comma before 'Excel.Application'. The script gets a reference to a running Excel application, lists open workbooks names and quits Excel. If there is no Excel instance running you will receive an error. This is also why you couldn't use GetObject() to get an instance of Scripting.FileSystemObject - there was no running instance.
You could use GetObject if there is an instance og Scripting.FileSystemObject already running in memory. Try this code:
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFso1 = GetObject("", "Scripting.FileSystemObject")
WScript.Echo TypeName(objFso)
WScript.Echo TypeName(objFso1)
You can see that you first need to use CreateObject() to and when FileSystemObject is running it is possible to get a reference to it, but this doesn't make much sense because you already have a reference to it (objFso). So, use CreateObject() to create an instance of FileSystemObject.
Note, that also GetObject()
accepts the following monikers in argument:
"iis:<metabasepath>"
- Allows a programmer to view and alter key IIS functionality for any webserver physically connected to this machine.
"java:<classname>"
- Returns a reference to an unregistered java object found in the %system root%\java\trustlib folder using the Java Virtual Machine.
"script:<absolutepath>"
- Returns a reference to an unregistered Windows Scripting Component or other supported script type.
"clsid:<clsid>"
- Returns a reference to an object by it's class ID in the registry.
"WinMgmts:<string>"
- Allows access to base Windows OS functionality with WMI.
"OBJREF:<base64encodedstring>"
- Returns access to a running object instance.
"queue:<clsid/progid>"
- Used to activate a queued COM+ component via MSMQ.
"new:<clsid/progid>"
- Allows instancing of any COM component supporting the IClassFactory pointer (including queued components).
source: http://web.archive.org/web/20021001133221/http://www.aspemporium.com/aspEmporium/tutorials/GetObject/index.asp