Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i prevent a VBScript from running standalone?

I'm doing a mash between VbScript and CMD, i can call the VBScript easily with

cscript.exe //NoLogo "%~dp0TASK.vbs" >>"%~dp0output.txt"

But I need to disable the feature of users clicking on the VBScript and calling all sorts of errors, rather than it being called through a batch file.

My first attempt was a mess of setting a variable into a text file before i ran cscript.exe and use error handling in VBScript to tell if that variable could be collected, but it added too much time to the script.

Does VBScript have a way to tell whether it was started by CMD, or simply by double clicking, and able to act accordingly?

like image 212
Bloodied Avatar asked Jan 18 '26 20:01

Bloodied


1 Answers

Here is a simple function, detecting the parent process caption. You can check if the process was started by CMD shell (the caption is cmd.exe) or by double-click (explorer.exe):

If LCase(GetParentProcessCaption()) <> "cmd.exe" Then WScript.Quit

' the rest part of your code here

Function GetParentProcessCaption()
    With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & CreateObject("WScript.Shell").Exec("rundll32 kernel32,Sleep").ProcessId & "'")
        With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & .ParentProcessId & "'")
            With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & .ParentProcessId & "'")
                GetParentProcessCaption = .Caption
            End With
        End With
        .Terminate
    End With
End Function

In the context of your question another method allowing to pass parameters from CMD shell process to WSH script child process may be useful. It uses environment variable and WScript.Shell object. Consider the below example.

There is code for task.cmd file:

set myvar=myvalue
wscript "%~dp0task.vbs"

And for task.vbs file:

WScript.Echo CreateObject("WScript.Shell").Environment("process").Item("myvar")

I have got the output as follows:

cmd shell output

wsh output

Note, process environment variables are accessible for child processes only.

like image 82
omegastripes Avatar answered Jan 20 '26 12:01

omegastripes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!