5

All I want to do is differentiate between the program being run by the command line or by clicking the test.vbs file in a window.

If you run the script by typing C:\testFolder\test.vbs in a command prompt, then I want the program to run differently than if you double clicked test.vbs in the testFolder.

Is there some system variable that I can use to differentiate between the two scenarios? I first attempted to use WScript.Fullname to determine if the pathname ended in cscript or wscript. But that didn't work so well.

Any ideas are greatly appreciated.

robbie
  • 658
  • 3
  • 11
  • 26
  • Why didn't that work so well? That is how you determine the host executable. – Josh Dec 31 '10 at 19:00
  • 1
    The problem with checking `WScript.FullName` is that if you run a script by just typing the script name at a command prompt, it will still be run using wscript.exe (assuming that's the default script host). You have to explicitly type `cscript test.vbs` to have it run using cscript.exe. – Cheran Shunmugavel Jan 04 '11 at 03:00

3 Answers3

5

You could try something like this:

Set WshShell = CreateObject("WScript.Shell")
Set objEnv = WshShell.Environment("Process")

msgbox objenv("PROMPT")

In general PROMPT will be set to something like $P$G when run from a command prompt, but left blank when you run the .VBS file directly.

Joel Spolsky
  • 33,372
  • 17
  • 89
  • 105
3

If you want to test against WScript.FullName, you can use InStr with vbTextCompare so that the match is case-insensitive.

If InStr(1, WScript.FullName, "cscript", vbTextCompare) Then
    WScript.Echo "Console"
ElseIf InStr(1, WScript.FullName, "wscript", vbTextCompare) Then
    WScript.Echo "Windows"
Else
    WScript.Echo "???"
End If
Tmdean
  • 9,108
  • 43
  • 51
  • You are assuming that a) the default script host is [WScript](http://stackoverflow.com/a/35189167/1851270), b) in the console the script is run with CScript. – antonio Jan 28 '17 at 10:18
0
i=(instrrev(ucase(WScript.FullName),"CSCRIPT")<>0)

returns -1 if running cscript, 0 if running wscript

Antoni Gual Via
  • 714
  • 1
  • 6
  • 14