robbie
robbie

Reputation: 668

How to tell the difference between a VBscript is run from command line or by clicking it in a window?

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.

Upvotes: 5

Views: 3264

Answers (4)

WScript.FullName contains absolute path to scripting host.


When script is launched using WScript scripting host, WScript.FullName contains "wscript" as substring, otherwise WScript.FullName contains "cscript" as substring.


LCase(WScript.FullName) is used to make case independent comparison.


bCScript = True
If InStr(1, LCase(WScript.FullName), "cscript", 1) = 0 Then
    bCScript = False
End If

' --------------------------------

If bCScript Then
    WScript.StdOut.WriteLine "CScript: " & WScript.Version
Else ' WScript
    WScript.Echo "WScript: " & WScript.Version
End If

MSDN: VisualBasic & WScript

Upvotes: 0

Antoni Gual Via
Antoni Gual Via

Reputation: 763

i=(instrrev(ucase(WScript.FullName),"CSCRIPT")<>0)

returns -1 if running cscript, 0 if running wscript

Upvotes: 0

Tmdean
Tmdean

Reputation: 9299

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

Upvotes: 3

Joel Spolsky
Joel Spolsky

Reputation: 33667

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.

Upvotes: 5

Related Questions