Why Can’t I Create The WScript Object?


/>

Every
now and then someone will ask me why the WSH shell object and the WSH network object
are creatable from Visual Basic, but the actual root
WScript object
is not.

 

I
am always completely mystified by why people ask this!  Why would you WANT to
create the
WScript object
in a VB app?  What would it do for you?  It isn’t creatable as an in-process
object because it represents the state of a WSH process, and a VB app is not a WSH
process!  The whole point of the
WScript object
is that it represents everything about the presently running Windows Script Host. 
You can get from it all kinds of properties: the name and version of the script host,
the path of the running script, the arguments which were passed in, the standard streams
of the process, and whether the script was set to time out or not.  None of
these properties make the slightest bit of sense to access outside of a running instance
of WSH!
  What the heck could this possibly mean?

 

Set WScript
= CreateObject(“WSH.WScript”)

Timeout
= WScript.TimeOut

 

The
timeout of what?  You’ve just got some object there, not a running instance of
the script host. 

 

What
about the methods on the object?  Again, all of them are deeply tied into the
underlying script hosting mechanisms. 
WScript.CreateObject, GetObject, ConnectObject and DisconnectObject manipulate
WSH-owned event sinks on the script dispatch.  I discussed yesterday how deeply
tied
WScript.Sleep is
to the underlying hosting mechanism, and
WScript.Echo is
not particularly interesting — there are better ways to create a message box in VB
already.

 

I
just don’t get it.  Why do people keep asking me to make the
WScript object
creatable?  I can’t figure out what they think they’re going to do with it once
they’ve created it and no one ever gives me a straight answer when I askIt’s
like asking for the ability to create the
Response object
without starting ASP!  What could it possibly mean to have a
Response object
but no web server process?  It doesn’t make any sense, so we don’t let you
do it.

 

We do provide
an object model whereby you can spawn off WSH processes (both locally and remotely)
and query their status as they run.  Perhaps that is what these people are looking
for?  Remote WSH is a complicated topic in of itself, so perhaps I’ll talk about
that in a later blog entry.

Comments (59)

  1. theCoach says:

    I have not proceeded far enough to know exactly what I want, but I will eventually need some mechanism in a VB component that takes some JScript or VBScript and executes it, then returns the result. Is there a some script object that will allow that?

  2. Eric Lippert says:

    Yes, the Microsoft Script Control is probably what you want. It provides a simplified interface to the script engines which you can use from VB. Here’s a magazine article, or do a google search to find the documentation.

    http://www.microsoft.com/mind/0799/script/script.asp

  3. Robert Stewart says:

    If I create a COM object using .wsc file, I can create the WScript.Shell object, but what if I would like to write to std out and read from std in (using base WScript object), from within my COM object written in JScript (it IS running in an instance of WSH isnt it?

  4. Eric Lippert says:

    No, WSCs do not run an instance of WSH. They are just COM objects like any other. Lots of people are confused by this. I’ll do a blog entry.

  5. Alex Angelopoulos says:

    A couple of points here about the real world "question behind the question" on this that seems to crop up frequently. Here’s the biggies I see in the newsgroups, and a couple might even be bloggable. :)

    + Misunderstanding of what WScript means. The progids for WshShell and WshNetwork indicate to people who are still weak on object references that they’re not allowed to use them outside of WSH – the same for the Dictionary and FSO to a certain extent. This is a big thing, because frankly all of those get used out the wazoo by coders since they are so handy. WshShell is hitting it big again since the Exec method was implemented as well..

    (2) The ubiquitous use of WScript.CreateObject in the help docs. OK, it’s a nice method with nice built-in event hookup, but using it for Scripting.FileSystemObject tends to catch cut’n’paste ASP programmers by surprise.

    (3) The Grass is Greener.

    A classic example of a truly useful tool is WSH’s argument parsing. Sure it’s got limitations, but it’s THERE. It’s also usage-centered. There’s no robust argument parser available to people wanting to start with a standard COM object from Microsoft.

  6. Some Guy says:

    The reason someone would want to create a WScript object in VB, is the reason I currently want to.

    I am using the MS Script Control to run a VB script file.

    The script file has WScript references in it.

    The MS Script Control throws an error "DescriptionObject required: ‘Wscript’" when it comes across a such a reference.

    The MS Script Control doesn’t know what Wscript is.

    It would be handy to create a Wscript object in VB and pass it to MS Script Control, so it could indentify it and run the script as intended.

    Am I missing something here?

    How do you run a VBS script from VB, when the script has a Wscript reference in it???

  7. Eric Lippert says:

    My question then would be "why are you doing that?" If you run a WSH script without WSH, it’ll fail. The same way that if you run an IE script without IE or an ASP script without ASP, it’ll fail.

    Why do you expect that you should be able to run a script that uses an object model and runtime environment from a program that lacks that OM and environment?

  8. Some Guy says:

    Why am I doing what?

    Trying to run a VB script from a VB app?

    Because it is a requirement of our system.

    I understand the problem at hand, I am just suggesting a reason why people may ask the question frequently.

    You would think in the wonderful world of COM there would be a simple way for VB to run a VBScript file.

    The incompatibility seems absurd.

    Please let me know if you have any insight on how to run a .VBS, from a VB app (or dll), where the .VBS file contains WScript functionality.

    Thank you.

  9. George says:

    I have tried very much to run a remote WSH script using the WSHController object, but I got the error message "ActiveX cannot create the object" when I tried the script from Windows 2000 server to Windows Me OS and I got the error "Permission denied " when I tried the script from Windows 2000 server to Windows professional OS.

    Please tell me what I can do to resolve this problem. I need to run my scripts from my server to the clients.

  10. Manu says:

    It would be usefull to have the scripting object in VB because this would permit to code program with intellisens, object viewer, compiler, syntax analysis….

  11. To Eric Lippert says:

    Here is the naswer to your question "Why would you WANT to create the WScript object in a " …. " app?"

    Because I want to to run user-defined .VBS screept but not to run them as separate process.

    There is no way you can do the Sleep if you cannot access WScript.

    The problem is the deficiencies in implementation of WScript and WSH where some important function are implemented on WScript level instead of the VBS level. You guys created the problem in the first place and then you keep asking "Why would you WANT" questions.

  12. Eric Lippert says:

    I think I see what you’re saying. You want to create an object that represents a script host IN PROCESS and run scripts, right?

    We wrote that object — it’s the Microsoft Script Control. You could probably write up your own script host in VB6 that runs multiple scripts in one process and has a "Sleep" method in about 100 lines of VB, or less.

  13. Advait Supnekar says:

    I am trying to run a similar code for MSI installed for a windows application in .net:

    Set oShell = WScript.CreateObject ("WScript.shell")

    oShell.run "regasm TestHarnessAPI.dll /tlb:TestHarnessAPI.tlb", 8, True

    This code registers the .net assembly as a type library. Is there any other way I can do that?

  14. Eric Lippert says:

    Just use regular old "CreateObject". Again, this is a case where the method only makes sense in WSH, and therefore we don’t let you use it outside of WSH. (WScript.CreateObject participates in the WSH event binding model.)

  15. Bart Ramharter says:

    I would like to use a sleep method in a script executed within a WMI consumer (the standard consumer ActiveScriptEventConsumer). You cannot use the Wscript object in those scripts either, and I would REALLY like something to pause execution. Why in hell did they not put the sleep method in WshShell or something????!!!!??? I really don’t have any other option besides using an external program (.exe), what I do not whish because it add another layer of ‘things that can go wrong’. So right now I’m trying to instantiate the WScript object inside the script, or trying to find something that waits for a trigger of some kind. Anybody any idea?

  16. Eric Lippert says:

    > Why did they not put the sleep method in WshShell or something

    I know this might be hard to believe, but in fact I am not a complete bozo. :-)

    I put it on the WScript object for a very good reason, which I blogged about here:

    http://weblogs.asp.net/ericlippert/archive/2003/10/07/53155.aspx

  17. Yor says:

    this article makes no sense to me. i like to think i’m not a complete bozo either Mr. Lippert, but I find this quite patronising. I do a lot of scripting, and sometimes I want to port that to VB with the minimum of fuss … quite simply, to answer your question "why would you want it ?", i would say "why not ?". let’s look at the situation :

    – methods/properties that make no sense within VB, let them generate an error. that’s fine, but method/properties that are sensible and reasonable, just let them work in VB. again (obviously ? quite simply ? intuitively sensible ?), just let the method/properties that make sense in vbscript function in VB and it instantly

    here’s another reason : "cos I don’t want to waste pointless hours re-creating the wheel, etc, every time I want to port some simple (but maybe large) vbscript into a vb project". if making WScript available inside vb means that we can port 99% of vbscripts in a very simple way into vb without recreating the wheel, sitting in front of computer screens for our entire lives not interacting with other human beings and stuff like that, then on my bozo-level, yes, I would want WScript available in VB for the above (obvious?) reasons.

    remember : as I note, if a part of script makes no sense inside vb, it generates an error. ummmm, obvious ? simple ? intuitive ??? obvious, simple, intuitive are things that appeal to my bozo-world-view. with the bozo-world-view of obvious-simple-intuitive, it would mean that we have to recreate only the parts that are essential, and it causes no complexity or overhead, it’s just sensible.

    if there are absolute reasons to not allow wscript in VB then fair enough, but for the above, and for trying not to waste my entire life having to recreate the wheel every time I move from vbscript to vb and vice-versa, then … why not, mr. lippert ??????

  18. Eric Lippert says:

    Would you also expect an ASP page written in VBScript to just work in VB? What about an IE web page written in VBScript?

    The Response object in IIS represents a web server. The window object in IE represents a web browser. The WScript object represents a script host. A VB program is none of these things, so VB doesn’t implement those object models!

    You seem to be implying that there are methods that would just work in VB — but we already put all those methods we put on other objects so that you could use them from VB. The only ones that remain are the ones that make no sense to use from VB because they rely on the hosting model in some way.

  19. Yor says:

    >>> Would you also expect an ASP page written in VBScript to just work in VB? What about an IE web page written in VBScript?

    yes, I kind of do, as it seems logical to me as a design process to make those things subsets of the larger development environment that is VB and I probably would have made that a basic design point and then there never would have been this argument, you never would have to answer this question, and I would easily be able to port things from asp/vbscript to vb etc.

    for example, I don’t think that you should ever have made the wscript object except as a way to access other objects. So, I don’t think that you should ever have allowed things like wscipt.echo, wscript.sleep and implemented them elsewhere. I seldom use wscript.echo / sleep, *but* it is very clear that you never ever needed them in the wscript object, sleep could easily been elsewhere and echo need never have existed. then, there are such things as constructs that I use in vbscript a lot like :

    sCurrentPath = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) – Len(WScript.ScriptName) – 1)

    I will always have to rewrite this in going to VB, but that was unneccessary with simple design goals to avoid constructs like that in wscript. If you had implemented the ScriptFullName and ScriptName parts in another place, this has complete relevance within VB in returning the location of where the compiled executable is. no ambiguity, but, since these elements are inside the wscript object a lot of thigns are messed up, and you will forever have to answer this question, and I and others will always have to rewrite our scripts. It seems to me a simple situation that could have been simply avoided with some simple basic approach to absolutely minimise the explicit ways that wscript could be accessed, wscript.echo was always pointless compared to msgbox and the shell popup method etc. I see your points completely, but the existence of things like echo, sleep, scriptfullname, scriptname etc etc are always going to hang around and be an unneccessary problem that need never have happened in the first place I think !

    I guess I’ll just have to be stuck with the rewriting, and you will be stuck with constantly having to answer this question that was created as a result of making these properties available, but I just wish that there was a simpler way to just grab my scritps and stuff them inside VB and get them working without having to fundamentally rewrite quite a lot of the parts ! :o(

  20. Yor says:

    I just had a look at the WSH documentation and wanted to check some of this with you ?

    From this page in the documentation : mk:@MSITStore:C:Program%20FilesMicrosoft%20ScriptingSCRIPT56.CHM::/html/wsobjwscript.htm

    Arguments Property

    – I see why this should be in the wscript object. I see your point here.

    Interactive Property

    – This is only relevant to a scripted process. I see your point here, *but* this could easily work inside VB as it simply diables all later WSH engine output and input. *simple* to have meaning within VB and VBScript (to *me*, but maybe there are good technical reasons why this could never have a sensible context from within VB ?).

    FullName Property, Name Property, Path Property, ScriptFullName, ScriptName, Version

    – Has complete relevance within VB or VBScript. I do not see any problem.

    In fact, for Name, FullName, Path, ScriptFullName, Version, Echo, Quit, Sleep have *completely unambiguous relevance within VB as well as VBScript. Don’t they to you ?i.e., I would argue that it is *very* relevant that I might want to know the location of the script engine (WScript.Path) or the name of the engine (WScript.Name) or the ScriptFullName (translates to the location of the currently running exectuable for the VB compiled code) or be able to do an Echo.

    Echo Method, Quit Method, Sleep Method

    Ok, Quit only has relevance within WSH, I see your point, and also Sleep is about the WSH engine’s operation, so I see that it’s not as sensible outside of that context, but VB could easily do the Sleep ! Surely, Sleep could easily function outside of the context of the WSH engine, i.e. it simply pauses program execution of course ! (that’s intuitively obvious, right !?) (however, again, for complex VB execution with multiple threads or something like that, this could be ambiguous and cause problems, so maybe there are good technical reasons why this could never have a sensible context from within VB ?).

    StdErr Property, StdIn Property, StdOut Property

    – ok, you say for these unambiguously in the documentation that "The StdErr property returns an object representing the standard error stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.". These will clearly never work in VB and quite rightly as it does it’s own seperate error handling. I completely see your point here, and this is unambiguously addressed in the documentation, hence completely clear.

    CreateObject Method, ConnectObject Method, DisconnectObject Method, GetObject Method

    – These already work from within VB right ? for calling objects etc.

    I have to say, with the above breakdown, I have a 100% conflict with your original proposal. There are *far* more reasons why many people would want these operations to work in an intuitive way from within the context of VB than to not work. It is very relevant that a VB project of mine might want to check the version of WSH installed on a system to act upon that information in my VB program ! etc etc, I see many many reasons where I would want to use the above intuitively within VB ! I’m trying to follow your argument, you are a longstanding senior Microsoft professional programmer, and I am just a MSI packaging consultant and System Administrator that does what I’m sure you would consider to be very simplistic code, but I do a lot of it, and in that regard, simple common sense leads me to the conclusion that most of the above has absolute and unambiguous (and *useful*) relevance within VB so I just can’t follow the statement "I am always completely mystified by why people ask this! Why would you WANT to create the WScript object in a VB app? What would it do for you?". Sure, for Arugments or Quit etc they only have relevance within WSH, I *completely* understand your point, but the others are very relevant in VB I would argue. I would have to say that I am completely mystified by *your* point here !

    p.s. Go easy on me, but I think I’m just making valid, sensible, intuitive points here. I’m no professional programmer like you, but I cannot at all understand the restrictions that you have *chosen* (clearly this is a design choice as most of the above have complete relevance within VB) to make as part of the WSH design process with the above points in mind !

  21. Divya says:

    even i have to run a .vbs from VB and i have done it like this

    set wshshell=wscript.CreateObject("wscript.shell")

    but i am getting the error "424:Object required."

  22. Eric Lippert says:

    I wrote another blog entry on why Sleep is part of the WScript object. There are good reasons why all of those are integrated into the hosting model.

    But more generally — sure, you’re right. It’s software. Anything is possible. We could have written a library that made VB6 act just like WSH. (Well, except for the fact that WSH was written several years after VB6. But we could have shipped VB7 with the "WSH compatible" feature.)

    We didn’t, because that would have taken years of work, cost tens of millions of dollars, and we had more important stuff to do. I’m sorry if we didn’t meet your needs, but there were only a tiny handful of developers, PMs, testers, writers, localizers, etc, working on the script technologies and we had our hands full implementing things like a richer project model, a security system, and remote access for WSH — all features that people were asking for a LOT. Very few people banged on my door demanding that we implement a new version of VB that was fully compatible with Windows Script Host. In fact, you’re the first one. And since there will never be a VB7, and I added the last new feature to WSH in September of 2000, I’m afraid that you’re going to have to live with disappointment.

  23. Eric Lippert says:

    To briefly sum up:

    Quit, Sleep, and all the object creation methods integrate with the WSH event handling and timeout model, which is completely different from VB’s eventing model. In VB, use Exit for Quit, loops with DoEvents for Sleep, GetObject and CreateObject for object creation and WithEvents for event binding.

    Echo has different behaviour in WScript and CScript. Use MsgBox in VB.

    And since VB6 programs are usually forms based, not console-based, the standard streams don’t really make any sense.

  24. Yor says:

    ok, Eric, but I never said that you should make VB do what *I* want or make VB7 and I never said that you should spend 10’s of millions to do what *I* want. I’m not that selfish, and I don’t see how you polarise it in that odd way. No, my point is simply … objects such as FileSystemObject were implemented *after* VB6 was made, so why could WScript not have been implemented in such a way to be accessible also !? As I understand it, some of the objects written for WSH were written *well* after VB6, but *they* are accessible from VB6, but you don’t say *that* should have not been made available in VB6. Creating the other WSH objects did not require VB7 and I am not advocating VB7 for WScript support either. ok, if you want to suggest that I am saying that I selfishly want Microsoft to do what I tell it to, and that I expect Microsoft to spend 10’s of millions on me, then you can say such things, but note that I never suggested it, you thrust that position onto me without me coming close to that suggestion.

    Oh, and I’m not going to live with disappointment, cos I really don’t care about it much. I won’t get asked this question over and over and be mystified by it, as I think it’s a sensible question, but you WILL get asked this question over and over, as come on, it’s an obvious question ! Anyway, a friend has implemented some function bridges in vb so that most of the wscript stuff will work as written or failover sensibly if I use his library, and so far that works perfectly for the wscript.scriptfullname etc type properties. So with a totally trivial addition like this, you could have avoided these questions that mystify you over the years completely !

    By the way, I see what you mean about echo, of course it’s useful for the cscript etc as you say, I didn’t think on that, but again, just to stress the point, I just thought that if FileSystemObject could be implemented *after* VB6 was written and be fully accessible from VB6 then it seems odd that WScript was chosen to be restricted in such a confusing way. My only point is that really, I think it’s odd to suggest that people "mystify" you by asking that question, as you chose to make that object inaccessible so it’s no wonder in light of the other objects availability that people just ask in a polite way "why?" (note : it’s just a question, not a demand for 10 million dollars of development). I never banged on any doors or asked for VB7 etc, and I can live with this limitation, but to be fair, I would say, it will always raise a question mark that you created this contradictory situation, not for me alone, but as people will *obviously* ask you this question over and over, since you chose to make that intuitively broken situation with *some* of these WSH objects created *after* VB6 to be accessible from VB6, but WScript to not be accessible.

    (I’m not certain that FileSystemObject was created after VB6, but I’m pretty sure it was from my memory of WSH development, and I don’t want a VB7 or for Microsoft to spend 10 million dollars on my ideas of what’s intuitive, in case I didn’t make that clear earlier …;o) I should keep stressing it though, it case i’m accused of selfishly wanting Microsoft to be my personal development team.).

    Your argument is reasonable, but it’s not completely sound. I think that it is NOT mystifying that people ask this question; it’s PERFECTLY *natural* that people ask it. Sorry, I *love* your blogs and all that, and have learned a huge amount from reading them, fascinating stuff, but on this one, I got confused on your initial point and I guess I still think it’s a completely reasonable question for people to ask ! :o)

  25. Yor says:

    Here is an example of what my colleague suggests for making some vb to emulate WScript :

    ‘ Here is Form1.frm

    ‘ =====

    Private Sub Command1_Click()

    MsgBox WScript.ScriptFullName

    End Sub

    Private Sub Form_Load()

    WScript.WScriptInitialise

    End Sub

    ‘ Here is WScript.bas

    ‘ =====

    Attribute VB_Name = "WScript"

    Public WScript As WScript_Type

    Private Type WScript_Type

    ScriptFullName As String

    End Type

    Function WScriptInitialise()

    WScript.ScriptFullName = App.Path

    End Function

    Function ScriptFullName()

    ScriptFullName = WScript.ScriptFullName

    End Function

    =====

    What do u think of this approach, Eric ? … it can only emulate so much, so it’s not going to be great, but with a small library to enable most of WScript operate in VB it would make it a lot simpler for me to import my VBScript to VB *and also* export it back to VBScript from VB, so I’m keen on expanding this to cover most of the WScript parts if possible … but you should have allowed this originally ! ;o) ;o) only kidding ! ;o)

    anyway, roll on Longhorn, in which the scripting language meets the full development environment … right ? in fact there is no distinction between the 2 as far as I can see, which is the way things should be in my opinion. the scripting is completely equivalent to full development it seems in .NET which is in a way what I would have liked vbscript to have been to VB6 (but I don’t want 10’s of millions in development of VB7 ! I just want 10 million for me …)

  26. Yor says:

    by the way, i didn’t say this is a good, it’s just a *crappy* hack to make porting simple vbscript to and from vb. as soon as you add any other vb in to the main form you could not take it to vbscript etc. it’s just a crappy hack, but if expanded could be useful for cut/pasting functions from vbscript into and out of vb that might reference the wscript object etc. that’s all it is intended to be for really. if a crappy hack sometimes serves a simple useful purpose, i’m gonna use it. don’t care much for purist nonsense. pragmatism over purism i say ;o)

  27. Eric Lippert says:

    Obviously I’m not explaining myself very well.

    The difference between the FSO and the WScript, the window object and the Response objects is that the FSO represents something external to the process — it represents the file system, which can be accessed via the operating system. The operating system has thousands of standard APIs for doing just that.

    The host-provided object models represent something about the INTERNAL state of the host and therefore must be provided by the host.

    How would you implement a cocreatable WScript object? In order to make it work, you’d need to know exactly what the compilation model, language model, eventing model and threading model the host had. There are no APIs to discover that information. The only sensible way to do it is to have the HOST expose that information in its own object model.

    Is that more clear?

  28. Eric Lippert says:

    Let me try an analogy. You’re driving along in your Honda Civic and you want to know what the exterior temperature is. You go to your local thermometer store, buy a thermometer and bolt it to the driver’s side door. You crank up the air conditioning and drive on.

    Later you buy an 18 wheeler Mack truck. You still want to know what the temperature is outside, so you unscrew the thermometer from the Civic and bolt it onto the driver’s side door of the Mack truck.

    Then you try to turn on the air conditioner and realize that you forgot to get the air option. No problem — you just take the air conditioner from the Civic, right?

    No! It doesn’t work that way. The air conditioner in a Civic is built specifically to take advantage of internal implementation details of the Civic engine. The control systems, the belts, the shape and position of the compressor, etc, are all specifically designed to fit into a Honda Civic.

    Your thermometer doesn’t depend on the engine — it depends on the framework of the vehicle having the right surface to bolt it to. It’s behaviour depends on factors external to the vehicle. But your air conditioner not only depends on the framework of the vehicle having a particular shape, it also depends on internal engine characteristics.

    The WScript object is a lot more like the air conditioner than the thermometer. In theory could you make a general-purpose, highly configurable air conditioner that would fit in both an 18 wheeler and a Civic hatchback? Sure, but it would be a whole lot more expensive than building the air conditioner into the truck in the first place.

    Is that more clear? I think you are majorly underestimating just how tied into the hosting model the WScript object is.

    Echo, sure, whatever, you could implement that in another host without too much difficulty.

    But what about WScript.CreateObject with event binding? How the heck are you going to do that without having access to the internal connection point array that a VB6 program maintains?

  29. I have a .wsf file which has several jobs inside it – it’s all working very nicely – certain jobs are scheduled to run weekly/ monthly (they email out CSV reports as an attachment). I also need the ability to trigger a .WSF script from a web page. I know this can be done through a shell type command, but I want to use the proper object. My code at the moment looks like this:

    Dim wsh As Object

    Dim oScript As Object

    wsh = Server.CreateObject("WSHController")

    ‘ oScript = wsh.CreateScript("C:InetpubwwwrootWebApplication1ReportsReports.wsf //Job:Consultancy_Report //d", "localhost")

    oScript = wsh.CreateScript("C:InetpubwwwrootWebApplication1ReportsReports.wsf", "martin")

    oScript.Execute()

    Dim sError As String

    sError = oScript.Error.Description

    This silently logs an error in the event log, whilst pretending to work on the web page:

    Unable to start a DCOM Server: {6F201542-B482-11D2-A250-00104BD35090}. The error:

    "Access is denied. "

    Happened while starting this command:

    C:WINDOWSSystem32wscript.exe -Embedding

    I get a different error when running it on a Windows 2003 server (where it will hopefully end up):

    System.Runtime.InteropServices.COMException: Server execution failed

    is shown on the actual web page this time.

    Any ideas – Martin.

  30. Eric Lippert says:

    I have been meaning to write a blog entry on that subject for a while, but putting it off because its kind of complicated. In order to not become "virus central", I put a lot of safeguards into Remote WSH — DCOM must be enabled. If you enable DCOM, WSH Remote is disabled by default. If you enable it, by default only the administrator can use it.

    Also, there might be DCOM restrictions when running from ASP, I’m not sure.

    I’ll write more details at some point.

  31. I spent all day on it yesterday and my final (although quite poor, yet ingenious) solution is as follows:

    In the file Broker_Report.vbs:

    ‘ <!– #Include File = "Constants.vbs" –>

    ‘ <!– #Include File = "VBS-Tools.vbs" –>

    ‘ <!– #Include File = "ZurichIFA-Tools.vbs" –>

    ‘ <%

    OpenDB

    SendBrokerReport

    CloseDB

    — code to do stuff here —

    ‘ %>

    Include the above .vbs file in a web page as it is (making sure it’s not in a directory where it’s served!)

    Now include this .vbs file with a bunch of others in the file reports.wsf:

    <package>

    <job id="Consultancy_Report">

    <?job debug="true" error="true" ?>

    <Script Language="VBScript" src="Constants.vbs" />

    <Script Language="VBScript" src="VBS-Tools.vbs" />

    <Script Language="VBScript" src="ZurichIFA-Tools.vbs" />

    <Script Language="VBScript" src="Consultancy_Report.vbs" />

    </job>

    <Job ID="Consultancy_Companies_Report">

    <?job debug="true" error="true" ?>

    The #Include statements are ignored in VBScript, yet used in the web pages. Windows scripting does the including via the .wsf file, meaning the script can be run from both web pages and WScript.

    Cunning, huh?

    Martin

  32. yor says:

    yep, it’s clear Eric, my cludge is silly, i know you’re right. I wasn’t expecting WScript.CreatObject to be replicated, just the parts that are replicatable to work and the parts that are not to be meaningless. Some parts of WScript are meaningfull from within VB, and some are not, so those parts could easily have meaning inside VB.

    By your own analogy, if, for some weird reason, my air conditioner unit had a funky Digitial Radio receiver built into it, I *could* take the airco from one vehicle to the other and still use the Digital Radio while never actually getting the airco to work, right ???

  33. ABabu says:

    Very simple requirement. I want to implement single sign on for my website. People have logged onto the network before accessing the website. So without explicitly asking for them to logon to the website i want to query what is the username/domain. All this is in ASP. Any pointers ? I don’t care if it is ADSI or WScript. Any ideas would be greatly helpful

  34. Eric Lippert says:

    I’m not sure I understand what you’re asking.

    If the user has already logged in to an NT domain then that information will automatically be sent to the server if the server is configured to use NT security. You shouldn’t ever see a password dialog box in IE if the user is already logged in to a domain and you’ve granted the authenticated user access to a server.

    Are you asking how you find out in the ASP page what the user is? That’s easy:

    user = Request.ServerVariables("LOGON_USER")

  35. Robert says:

    RE: Wscript.Sleep in .wsc component

    Here is a quick and dirty way to sleep within a script component, which is really a call to another script outside of the component.

    Procedure with component creates Wscript.Shell object, which is used to run a separate VBScript that just contains Wscript.Sleep

    Component code:

    Sub TestSleep

    Dim WshShell

    Set WshShell = CreateObject("WScript.Shell")

    WshShell.Run "wscript.exe C:*TestSleep.vbs", , true

    End Sub

    TestSleep.vbs code:

    WScript.Sleep 5000

    Note: this of course does not solve issues of event handling, etc…

  36. Brian says:

    Robert,

    Your "quick and dirty" method for calling sleep was a *HUGE* help for me! Thank you so much for your slick work-around for something that shouldn’t have been reliant on Wscript.

  37. Steve says:

    How sad… I hoped a WScript object might give me a workaround for some WMI timeout problems.  If I could create a WScript object in VB and do the WMI call from there, then maybe my problems would be solved.  Unfortunately, this blog erased all hope of that experiment.

  38. EricLippert says:

    If you want to create a script engine from VB, use the Microsoft Script Control.  You can write a VB-based script host in about three lines of code with the Script Control. However, I don’t see how that’s going to help your timeout problem.  The script will run in the same thread as the rest of the VB process.

    My advice would be to find a WMI forum and pose your problem to them.  

  39. mf says:

    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

    Private Sub Command1_Click()

       MsgBox "begin"

       Sleep 10000

       MsgBox "end"

    End Sub

    This won’t spike your cpu usage either.

  40. rektide says:

    the issue is really trivial.  asp classic never implemented its own sleep function.  for a runtime that needs to be running async XMLHTTP requests & performing other async ops, not being able to enter a waitstate is… bloody criminal.  wsh is sweet, its just tragic the asp runtime is comparatively barren.  i’m sorry most people dont understand the discrepancy, but i hope you can understand asp users’ frustration at a functionally incomplete runtime.  hopefully you can forgive people for not understanding that they’re two totally seperate runtimes.  you did such a good job with WSH’s exposed api that asp couldnt match up.

  41. if all you need is a simple sleep() function within ASP object model, you can use the WScript Shell popup sub timeout property to implement. It’s a dirty hack, but if your w3svc service doesn’t have "interact with desktop" property enabled you won’t see anything on the console, and it’ll do the trick for you without any impact on the CPU.

    I was just wondering if the inner loop inside Popup does a call to win32::Sleep() and wait for events triggered by the popup window itself, or it has any additional overhead.

    any ideas?

    —–

    <pre>

    script started.

    start: [<%= time() %>]

    waiting 10 seconds…

    <%

              Set objShell = Server.CreateObject("WScript.Shell")

              objShell.Popup "", 10

    %>

    finish: [<%= time() %>]

    script terminated.

    </pre>

  42. Brett Hacker says:

    Just to get it this out there because I searched EVERYWHERE and couldn’t find a reference to this:

    It appears that the bug referenced in KB 311269 (enabling remote script host by running "wscript -regserver") is also present in Windows Vista, but just running that command isn’t sufficient due to all the UAC stuff. My workaround was to create a cmd file, "regservice.cmd" with a single line, the "wscript -regserver", then right-click that command file and choose "run as administrator". Evidently UAC wasn’t bright enough to prompt for access on wscript, since it didn’t know that the command line "-regserver" would require administrator access.

    Hope this helps somebody.

  43. A G says:

    Let’s forget Sleep in VB. I need Sleep in VBScript that is not bound to VB or WScript.exe. I have  third party product that implements user exits via VBScript (don’t have to license VBA) so I have to live within the cobstraints of their developers who don’t provide a Sleep feature. I know i’ve seen a mechanism for instantiating WScript in an old vb 4 or 5 book; it’s a wierd hack, and i’ve used it, but i can’t find my copy of the usage. Sleep is the one function missing from VBScript that is needed outside WScript.

    I know it can be done, it has been published, please just show us how.

    thanks

  44. Xameleon says:

    to A G: I found 2 ways of solving this problem.

    First:

    WScriptShell.Popup "Sleep",1,"Waiter"

    When using it in ASP, it doesn’t show any windows, but make a timeout for 1 second, so "Loop" or "For Next" can’t use 100% CPU

    Second:

    Basicly use COM coponent with Sleep function in it.

    I still searching for using Wscript.Sleep in ASP.

    to Eric Lippert’s

    is it possible to use WScript.CreateObject() with Event handling and WScript.ConnectObject and so on, as in VBSript ?

    P.S Excuse my english please. I’m russian.

  45. adialji says:

    I need to get the Local machine name of the client using vbscript.

    Then how to get the machine name without creating an obeject to the wscript.network?

    How ever the vbscipt is not allowing me to create the object.

    How come i can get the local machine name of the client

  46. Al says:

    for example, I’d like to use   WScript.ScriptFullName in HTA. How I can do it?

    It doesn’t work, but it can be very useful

    <html>

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

    <title>My HTML Application</title>

    <script language="vbscript">

    name.InnerHTML = WScript.ScriptFullName

    </script>

    <hta:application

    applicationname="MyHTA"

    border="dialog"

    borderstyle="normal"

    caption="My HTML Application"

    contextmenu="no"

    icon="myicon.ico"

    maximizebutton="no"

    minimizebutton="yes"

    navigable="no"

    scroll="no"

    selection="no"

    showintaskbar="yes"

    singleinstance="yes"

    sysmenu="yes"

    version="1.0"

    windowstate="normal"

    >

    </head>

    <body>

    <!– HTML goes here –>

    <p id="name"></p>

    </body>

    </html>

  47. All of the comments here that support accessing the WScript object or it’s functions are classic examples of over thinking a problem.  There is absolutely no need for the WScript object outside of the WSH environment.

    The most recent comment was that it would be nice to have the script name available from with an HTML Application.  The fact is that you already do.  Remember that HTAs run using an instance of the IE engine, therefore most browser capabilities are available to you.  Here’s a simple, reusable function for use in an HTA.

    Function ScriptFullName

    strLocation = Replace(window.location, "%20", " ")

    strLocation = Replace(strLocation, "/", "")

    ScriptFullName = Right(strLocation, Len(strLocation) – 8)

    End Function

    The window.location property is used to return the URL to the current HTA.  This needs to be formatted since it is an encoded URL.  I replace the %20 entity with a space and convert the backslashes to forward slashes.  Finally, I remove the file:/// protocol.

    As for a Sleep function, there are several reusable sleep functions available with a quick Google search.  In a most simplistic form, you can create one using the Time functions.

    Sub Sleep(intSeconds)

    dteStart = Time()

    dteEnd = TimeValue(dteStart) + TimeValue(intSeconds)

    While dteEnd > Time()

    DoNothing

    Wend

    End Sub

    Sub DoNothing

    ‘While/Wend has quirks when it is empty

    End Sub

    This simply takes an integer number of seconds and adds it to the current time.  It then loops over an empty subroutine until the end time is reached, indicating that the amount of sleep time has elapsed.  I’ve had to create an empty subroutine because the While/Wend doesn’t function properly if it is empty or only contains comments.

  48. The latest comment gave me a reason to revisit this post so I thought I’d add a little more useful information.  As I’ve said before, the WScript family of objects is not necessary in pure VB, however, the WshShell object (specifically the Popup method) IS very useful in VBA.  VBA does not provide a method of creating message boxes through the Windows API but the WshShell object’s Popup method provides us with a scriptable object that can.  Here’s how to use it.

    ‘Early bound to "Windows Script Host Object Model"

    Dim WshShell As IWshRuntimeLibrary.WshShell

    Set WshShell = New IWshRuntimeLibrary.WshShell

    ‘Or shorter syntax for early binding…

    Dim WshShell As New IWshRuntimeLibrary.WshShell

    ‘Using late binding (no reference)

    Dim WshShell As Object

    Set WshShell = CreateObject("WScript.Shell")

  49. texhood says:

    I would just like to see some simple examples of how to translate from WScript calls to .NET equivalent code.  I have NO background in scripts, just need to reproduce teh functionality in .NET.  Are there any articles or resources to enlighten one about the topic?  And about how to work with Active Directories in .NET?

  50. Bob in DC says:

    I am trying to find out the userid and domain of user who is using my web page The user is running IE from a remote workstation.  My web page resides on a windows 2003 server.

    my page is called whoisuser.html and contains vbscript.  It is running in default web directory under IIS V6.0

    I am trying by any means to get username and any other known information about the user.  THis is just one of many I have tried.  All run fine if they are alone in a .vbs file but fail if I try to run them in the script section of an html page.

    <HTML>

    <HEAD>

    <TITLE>Determine userid</TITLE>

    <SCRIPT LANGUAGE="VBScript">

    document.write("<h1>Who Is User</h1>")

    Set oWshShell = CreateObject("WScript.Shell")

    MsgBox oWshShell.ExpandEnvironmentStrings("User name=%UserName%")

    </SCRIPT>

    </HEAD>

    </HTML>

    Thanks in advance for any help you can provide.

  51. Mathis says:

    Remove the Wscript from the CreateObject so instead of Wscript.CreateObject("Wscript.Shell") just use CreateObject("Wscript.Shell")

  52. MaryK says:

    I’ll tell you why.

    I’m trying to use SAP Business Objects, specifically, to rename an exported report to something that includes a custom string.  I have a VB script that creates the string and renames the file.  The VB script needs to accept arguments.  It all works fine from the command line.

    Business Objects has this feature where you can embed a "Program File" for later use, which can be an .exe, Java, or a script file such as VBScript or JavaScript.  When I try to use my VBScript file and pass it some arguments (and the Business Objects interface gives you a place to put the arguments), I get the old "Variable not defined – WScript" error.  Nobody has been able to tell me how in the heck I can pass arguments to a VBScript file without using the WScript object.  I have had to resort to creating a VB script file for each different filename situation  instead of simply one script to which i can pass parameters.  Maddening.  If I had a gun I would shoot my computer right now.

  53. Olivier Mengué (dolmen) says:

    @MaryK: each scripting host exposes its environment in its own way. WSH exposes it through 'WScript'. IE exposes it through 'window'.

    Business Objects has its own way. You should have a look at the documentation of the scripting API of product and report issues to SAP. Microsoft can't do anything for you in this case.

    @Robert "Nilpo" Dunham:

    For HTA applications, the scripting host is IE. So you can (should) use window.setTimeout().

  54. Dirk says:

    Reading all that stuff, it is still unclear to me, why I can have a script including e.g.:

    WScript.Sleep 5000 that works when launched from cmd-line.

    But raises an error: "Object required: 'WScript'Line: 79", when used within a ScriptControl (AddCode).

  55. chip_w says:

    Ok, here's mine. I want to invoke a VB script from powershell using MSScriptControl. I want to produce debugging output from the VB script and WScript.Echo seems like it'd be the obvious way to do it. Unfortunately MSScriptControl doesn't seem to provide a environment object t (which would need to hook up to it's host environment)

  56. RCMorey11 says:

    The only feature of WScript that I'd like to be able to use in VBScript is .ScriptName.   I use a 3rd party software tool, Docklight, that has custom built in functions but can also run VBScript.  There is a script file (.pts) and a data file (.ptp)  that are linked together.  When I run the script file I'd like to be able to get the filename of the script file so I can create the file name for the data file and open it.  Right now I have to add a variable with the file name in every script file, but it would be a lot easier to just use something like WScript.ScriptName and be done with it.

  57. Olivier Mengué says:

    @NoSimDash @RCMorey11 @dirk

    Read again what I wrote.  The WScript object is only available when running from cscript.exe/wscript.exe.

    To put it clearly; what you are asking is impossible.