我可以将参数传递给 VBScript(用 cscript 启动的 vbs 文件)吗? [英] Can I pass an argument to a VBScript (vbs file launched with cscript)?

查看:24
本文介绍了我可以将参数传递给 VBScript(用 cscript 启动的 vbs 文件)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将此脚本保存在test.vbs"中:

I have this script saved in "test.vbs":

Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(workFolder &"\test.txt", 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing

当我运行脚本时,我想传递workFolder"变量的值.

When I run the script I want to pass the value of the "workFolder" variable.

我该怎么做?我可以做吗?可能是cscript test.vbs workFolder:'C:\temp\'"之类的?

How can I do this? Can I do it? Something like "cscript test.vbs workFolder:'C:\temp\'" perhaps?

额外的问题:是否有必要使用Set workFolder = Nothing"来清理传递的变量,或者 VBSCript 在终止时是否会自动执行此操作?也许Set File = Nothing"和Set FSO = Nothing"也是不必要的?如果您知道这两个问题的答案,请告诉我.

Bonus question: Is it neccessary to clean up the passed variable with "Set workFolder = Nothing" or does VBSCript do that automatically when it terminates? Maybe "Set File = Nothing" and "Set FSO = Nothing" is unneccessary also? Please let me know if you know the answer to both these questions.

推荐答案

您可以使用 WScript.Arguments 来访问传递给脚本的参数.

You can use WScript.Arguments to access the arguments passed to your script.

调用脚本:

cscript.exe test.vbs "C:\temp\"

在你的脚本中:

Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)

不要忘记检查是否确实有参数传递给您的脚本.您可以通过检查 Count 属性来实现:

Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:

if WScript.Arguments.Count = 0 then
    WScript.Echo "Missing parameters"
end if

如果您的脚本在关闭文件后结束,则无需将变量设置为 Nothing.当 cscript.exe 进程终止时,资源将被自动清理.将变量设置为 Nothing 通常只有在您明确希望在脚本执行期间释放资源时才需要.在这种情况下,您可以将包含对 COM 对象的引用的变量设置为 Nothing,这将在您的脚本终止之前释放 COM 对象.这只是对您的奖励问题的简短回答,您可以在以下相关问题中找到更多信息:

If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:

是否需要在 VBA 函数中将对象设置为 Nothing

什么时候必须将变量设置为Nothing"在 VB6 中?

这篇关于我可以将参数传递给 VBScript(用 cscript 启动的 vbs 文件)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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