如何防止VBScript独立运行?
我在VbScript和CMD之间做一个混合,我可以轻松地调用VBScript
I'm doing a mash between VbScript and CMD, i can call the VBScript easily with
cscript.exe //NoLogo "%~dp0TASK.vbs" >>"%~dp0output.txt"
需要禁用用户点击VBScript并调用各种错误的功能,而不是通过批处理文件调用它。
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.
我的第一个尝试是一个混乱在我运行 cscript.exe
之前将变量设置为文本文件,并在VBScript中使用错误处理来告诉是否可以收集该变量,但是它为脚本添加了太多时间。
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.
VBScript有一个方法来告诉它是由CMD启动,还是双击,并能够相应地执行?
Does VBScript have a way to tell whether it was started by CMD, or simply by double clicking, and able to act accordingly?
这是一个简单的函数,检测父进程标题。您可以检查进程是否由CMD shell启动(标题为 cmd.exe
)或双击( explorer.exe
):
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
在您的问题的上下文中另一种方法允许从CMD传递参数shell进程对WSH脚本子进程可能有用。它使用环境变量和 WScript.Shell
对象。考虑下面的例子。
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.
有 task.cmd
文件的代码:
set myvar=myvalue
wscript "%~dp0task.vbs"
并且对于 task.vbs
文件:
WScript.Echo CreateObject("WScript.Shell").Environment("process").Item("myvar")
我的输出如下:
注意,进程环境变量只能用于子进程。
Note, process environment variables are accessible for child processes only.