如何防止 VBScript 独立运行? [英] How do i prevent a VBScript from running standalone?

查看:18
本文介绍了如何防止 VBScript 独立运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 VbScript 和 CMD 之间进行混搭,我可以使用

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:\.
ootCIMV2:Win32_Process.Handle='" & CreateObject("WScript.Shell").Exec("rundll32 kernel32,Sleep").ProcessId & "'")
        With GetObject("winmgmts:\.
ootCIMV2:Win32_Process.Handle='" & .ParentProcessId & "'")
            With GetObject("winmgmts:\.
ootCIMV2: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.

这篇关于如何防止 VBScript 独立运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆