Does anyone know the reasoning behind having the option using:
Wscript.CreateObject("some.object")
and
CreateObject("some.object")
within VBScript? when I find documentation or examples that use Wscript.CreateObject, I usually rewrite using CreateObject, because it always seems to work, and then I can easily reuse the code within an HTA or ASP. But I've always wondered why this feature existed and if what difference it makes if you use one way or another within VBScript.
There's no difference between the two, when you call them with just one argument. The do exactly the same thing.
The difference between the two is only in evidence if you call with two parameters. The statements
Wscript.CreateObject("some.object", "AnotherParam")
and
CreateObject("some.object", "AnotherParam")
do completely different things:
The VBScript CreateObject function interprets the second parameter as a remote computer name and tries to create the named COM object on that remote computer; in this example, it tries to instantiate an instance of an object with ProgId of "some.object" on a remote computer named "AnotherParam". The WScript CreateObject method interprets the second parameter as a subroutine prefix to be used in handling events from the object. The two GetObject functions are similarly related.
(Adapted from TechNet,
section "Comparing VBScript CreateObject and GetObject Functions with WSH".)
I guess that the WScript object has the CreateObject method so any Windows Script language can create COM objects.
VBScript has that ability as a global function, but other Windows Script host languages might not.
For instance, JScript does not have a global CreateObject function (I believe) (it does, however, have a var a = new ActiveXObject("...") syntax, so you do not need to use WScript.CreateObject in JScript either).
I would guess there is no difference between the two functions.
EDIT: There is a difference (but only if you're trying to instantiate DCOM objects on remote hosts), see the answer by #Thomas Petersen.
JScript does not have a global CreateObject ?
WScript can't use JScript ?
Code from devGuru
// JScript
var objIE = WScript.CreateObject("InternetExplorer.Application","objIE_")
objIE.Visible = true
while (objIE.Visible){
WScript.Sleep(500);
}
function objIE_NavigateComplete2(pDisp, URL){
WScript.Echo("You just navigated to", URL)
}
function objIE_OnQuit(){
boolBrowserRunning = false ;
}
Related
I have an old ActiveX Component written in VB6 to support (don't even bother asking to modernize it, that's just what I have currently) and it does some weird stuff when compiling the following code:
Dim connectedPrinter As printer
Dim printers() As String
For Each connectedPrinter In printers
printers(UBound(printers)) = connectedPrinter.DeviceName
Next
All it should do is make a list of all connected printers. But, when compiling, VB6 tells me that
For Each control variable on arrays must be Variant
What's odd about that is, that in another function of the same codebase, I use the exact same loop for a different task (setting the current printer als default)
Dim pPrinter As printer
For Each pPrinter In printers
If (pPrinter.DeviceName = sPrinterName) Then
Set printer = pPrinter
Exit For
End If
Next
Yet, that is accepted without hesitation, compiles and also demonstrably works in the production environment.
What's going on here?
In the problem snippet, you have a local array called printers hiding the Printers collection. You can rename the local array, or qualify access to the collection by referring to it as VB.Printers.
Not using QTP myself, but trying to answer this question, I desperately need to know, whether this valid VBScript:
Class C
Function init(x, y)
Set init = Me
End Function
End Class
Dim o : Set o = New C.init(0, 1)
will cause a syntax error in QTP - or more generally: Does QTP implement its own dialect of VBScript?
This is valid in QTP too.
QTP uses VBScript as the engine for running tests, there are some extensions on the language that allow using test objects but most of these just look like global functions and objects. As far as I know nothing is removed from VBScript.
The limitations QTP has regarding class types are regarding intellisense and such not execution of the test/script.
I have two vbscript files, file1.vbs and file2.vbs
In a.vbs, I have the following code:
dim a : a = 1
function myFunction(k)
...
end function
call myFunction(a)
So file1.vbs can actually run standalone. Now in file2.vbs, I want to call myFunction(k) that resides in file1.vbs. However, when I import file1.vbs in file2.vbs, the calling myFunction is also imported, resulted in running myFunction automatically with parameter "a"... This is not what I want, because I might give a different parameter to myFunction, say "b".
How should I structure the program such that file1.vbs can run standalone, while file2.vbs can also call myFunction in file1.vbs but with different input parameter? Thanks.
The best way, in my opinion, would be to have library/module .vbs files containing only reusable subs/functions/classes but no top level (immediately executed) code. User .vbs files import libraries via ExecuteGlobal on .ReadAll() as shown in this Microsoft TechNet post.
(Also see Execute which has similar functionality but can also define objects and variables that have local scope.)
If you insist on mixing module and top level code, you can use a Pythonic idiom and compare the current WScript.ScriptName against a string literal and call the appropriate 'top level code' only when they match.
I need to write some vbscripts in my new project. I was told by other people that vbscripting is easy, but seems to me, it is not. For example, in the following example (provided by microsoft), these functions: CreateObject, CreateShortcut, as well as these property names: TargetPath, WindowStyle, Hotkey, etc, are used, but I just cannot find the corresponding API documentation about how to use them. In other words, how do you know you need to call these functions in your vbscripts? Visual Studio 2008/2010 do not have templates for vbscript either. Could anybody tell me what I am missing, and what the best way is to do vbscripting?
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop _
& "\MyExcel.lnk")
oShellLink.TargetPath = _
"C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE"
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = _
"C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE, 0"
oShellLink.Description = "My Excel Shortcut"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
Take a look here (MSDN).
The objects you are working with are documented there (of course, it's MSDN documentation so it's not ideal, but it's documented nevertheless).
Specifically the WshShortcut Object and the WshShell etc.
I don't think VBScript is a very easy language, especially if you need to write larger scripts.
If you don't specifically need to write a script but it would be ok with an executable I'd look at using VB.Net instead, where you have a good development environment that makes everything much easier since you have Intellisense and you can just press F1 for the documentation. And since it's a typed language with a large framework it gets easier to avoid mistakes and many operations you need you can just call a method in the framework rather than writing your own code.
However, if you do need to do it in VBScript, I'd suggest trying to find some kind of IDE for it. I haven't used any, but at least this one seems worth looking at.
The language of VBScript is relatively easy. It's a subset of Visual Basic and VBA and simplifies some things from those environments (eg you don't need to declare variable types).
What you are dealing with above is working with the methods and properties of a given object, WshShell. There are many many objects out there, each with their own set of methods and properties to know about, many with common usage conventions, and many more with "unique" (ie idiosyncratic) usage requirements. This is where the complexity comes in, but it's not part of VBScript itself. You will run into this with any other language (JScript, Python, Delphi) that works with the myriad objects and APIs that are out there for Windows system management.
The plus side is that once you get used to the language of VBScript and the process of looking up object API references and examples on MSDN and other sites, it does become very easy to put together complicated and powerful scripts.
Like I frequently tell users, computers often make things faster the second time you do something. The first time usually requires some learning.
A great set of resources for learning VBScript and how you need to approach things is the
TechNet Script Center, their Hey, Scripting Guy! series, and the Script Repository.
I need to write some scripts for WinXP to support some of the analysts here at Big Financial Corp. I need to decide which type of Windows scripting best fits my needs.
My needs seem pretty simple (to me anyway)
run on WinXP Pro SP2 (version 2002)
not require my users to install anything (so PowerShell is out. Likewise Perl, Python, and other common suggestions for these types of questions on Stack Overflow)
written in a non-compiled language (so users have a chance to modify them in the future)
reasonably complete language features (especially date/time manipulation functions. I would like to also have modern concepts like subroutines, recursion, etc)
ability to launch and control other programs (at the command line)
From my hurried review of my options, it looks like my choices are
VBScript
WScript
JScript
I don't have time to learn or do an in-depth review of these (or whatever else a standard install of WinXP has available). I need to pick on and hack something together as quickly as possible.
(Current crisis is the need to run a given application, passing several date parameters).
Once the current crisis is over, there will be more requests like this.
Edit
My current skill set includes Perl, JavaScript, and Java so I'm most comfortable using something similar to these
Edit
OK. I'll try writing a WSH file in JScript. I'll let you know how it goes (and figure out accepting an answer) once things settle down around here a bit.
Edit
It all worked out in the end. Thanks for the quick responses folks. Here's what I gave my user:
<job id="main">
<script language="JScript">
// ----- Do not change anything above this line ----- //
var template = "c:\\path\\to\\program -##PARAM## --start ##date1## --end ##date2## --output F:\\path\\to\\whereever\\ouput_file_##date1##.mdb";
// Handle dates
// first, figure out what they should be
dt = new Date();
var date1 = stringFromDate(dt, 1);
var date2 = stringFromDate(dt, 2);
// then insert them into the template
template = template.replace(new RegExp("##date1##", "g"), date1);
template = template.replace(new RegExp("##date2##", "g"), date2);
// This application needs to run twice, the only difference is a single parameter
var params = ["r", "i"]; // here are the params.
// set up a shell object to run the command for us
var shellObj = new ActiveXObject("WScript.Shell");
// now run the program once for each of the above parameters
for ( var index in params )
{
var runString = template; // set up the string we'll pass to the wondows console
runString = runString.replace(new RegExp("##PARAM##", "g"), params[index]); // replace the parameter
WScript.Echo(runString);
var execObj = shellObj.Exec( runString );
while( execObj.Status == 0 )
{
WScript.Sleep(1000); //time in milliseconds
}
WScript.Echo("Finished with status: " + execObj.Status + "\n");
}
// ----- supporting functions ----- //
// Given a date, return a string of that date in the format yyyy-m-d
// If given an offset, it first adjusts the date by that number of days
function stringFromDate(dateObj, offsetDays){
if (typeof(offsetDays) == "undefined"){
offsetDays = 0;
}
dateObj.setDate( dateObj.getDate() + offsetDays );
var s = dateObj.getYear() + "-"; //Year
s += (dateObj.getMonth() + 1) + "-"; //Month (zero-based)
s += dateObj.getDate(); //Day
return(s);
}
// ----- Do not change anything below this line ----- //
</script>
</job>
Clearly it could be better... but it got the job done and is easy enough for my user to understand and extend himself.
These are all technically the same thing with different syntax. Actually WScript/CScript is the engine, VBScript and JScript are the languages.
Personal opinion only follows: My personal recommendation is JScript because it reminds me more of a real programming language, and makes me want to punch myself in the face less often than VBScript. And given your familiarity with javascript, your best bet is JScript.
Going into a bit more detail about the difference between WScript and CScript as others have: these are your execution platforms for your scripts for the Windows Script Host. They are essentially the same thing, whereas WScript is more GUI oriented, and CScript is more console oriented. If you start the script with CScript, you will see a console window, but you still have access to GUI functionality, whereas if you start with WScript, there is no console window, and many of the default output methods display as windowed objects rather than a line in the console.
If you like JavaScript, you'll probably be ok with JScript. It's a decent language, and certainly more suitable for complex scripts than VBScript.
However, Microsoft1 hates JavaScript, so you'll encounter some APIs that are trivial to use with VBScript but painful to access using JScript. Consider yourself warned...
As snicker notes, WScript is the engine that drives both.
1 Anthropomorphization used to note general lack-luster support; not to be interpreted as evidence of any official policy.
Although JScript is a much less horrible language than VB Script, the problem is that VB Script has a more complete library of helpful functions built into it for things like date and number formatting. So it's not actually as easy a choice as it first appears, unless you are able to write and install your own library of helper objects to use with JScript.
Some details here.
Don't forget CScript. And be careful here, because the windows scripting host is often disabled by group policy at large companies. If that's the case, the only option that fits all your criteria is (shudder) batch.
If none of those work out for you, your best option is probably a compiled program where you distribute the source with the program.
Use JScript. A key difference between using JScript with the WScript/cscript engine and writing JavaScript in the browser is that you don't have the browser security restrictions. You also have access to ActiveX/COM objects for manipulating applications, the registry, etc. In fact, you'll probably spend a lot more time reading up on those custom objects and interfaces than worrying about the language features. Of course, you get all the benefits of JavaScript dates, regex's, etc.
A sample JScript app from MSDN might help to get you started.
Unfortunately, most of Microsoft's sample scripts tend to be VBScript, but the syntax is pretty easy to follow, especially if you're just trying to pick out COM interface details.
To expand on the other's answers a bit, WScript and CScript are programs used to run scripts written in VBScript (Visual Basic like syntax) or JScript (JavaScript-like syntax). CScript runs scripts from a console window, so that the Echo command writes to the console, whereas WScript runs them without a window and the Echo command writes to a popup message box.
You can write WSH (Windows Scripting Host) and WSC (Windows Scripting Component) scripts that use both VBScript and JScript by combining them in an XML-based wrapper, if you need to merge pre-existing code in the two languages.
You can also write HTA scripts, which stands for "HyperText Application". These are script code in an HTML file with the HTA extension that runs in Internet Explorer, which allows you to provide an interface using HTML controls, but also have complete access to your system because the run locally.
All of these are based on the Windows Scripting Host and Active Scripting technologies which have been included with all Windows computers since Windows 98. Along with fairly powerful base languages, they also give you access to WMI for extensive system and network information and management, and COM capability for automating Word, Excel etc. Also you can use ADO and ADOX to create and work with Access MDB files even if Access is not installed.
My choice would be WSH using JScript. You could use VBScript, but why, when JScript is available.
Here is a reference for Windows Script Host.