检索 VBScript 的参数

问题描述 投票:0回答:2

如何在不使用

cscript.exe
的情况下从 VBScript 传递和返回参数?

例如,我想从 script1 调用 script2,将值返回给 script1,而不涉及

cscript.exe
。 我搜索了各种答案,但它们在某种程度上涉及
cscript.exe
的使用。

此脚本获取已安装的语音并设置文件中提供的语音

voice.txt

Set WshShell = CreateObject("WScript.Shell")
WShShell.CurrentDirectory = "..\Confirmatory Texts"

Set FSO = CreateObject("Scripting.FileSystemObject")

If FSO.FileExists("voice.txt") Then
  Set temp = FSO.OpenTextFile("voice.txt")
  confirm_voice = temp.ReadLine()
  temp.Close

  Set Sapi = CreateObject("SAPI.SpVoice")

  For Each Voice In Sapi.GetVoices
    i = i + 1
  Next

  For loopvar = 0 To i-1
    If loopvar = CInt(confirm_voice) Then
      Set Sapi.Voice = Sapi.GetVoices.Item(loopvar)
    End If
  Next
Else
  WScript.Echo "An Error Occured"
End If

如果我从另一个脚本调用此脚本,如何使此脚本向调用它的脚本返回一些值?

vbscript arguments
2个回答
2
投票

VBScript 并不真正提供其他 VBScript 文件的调用或导入机制。最接近的是读取另一个文件的内容并通过

ExecuteGlobal
.

运行它们

演示:

将以下两个文件放在同一目录下并运行

script1.vbs
。它将读取
script2.vbs
的内容,并通过
Square
运行代码,使函数
ExecuteGlobal
在全局范围内可用。一旦该函数在全局范围内可用,您就可以在脚本的其余部分中使用它。

script1.vbs

Set fso = CreateObject("Scripting.FileSystemObject")

dir    = fso.GetParentFolderName(WScript.ScriptFullName)
script = fso.BuildPath(dir, "script2.vbs")

ExecuteGlobal fso.OpenTextFile(script).ReadAll  '"import" code into global scope

WScript.Echo Square(3)

script2.vbs

Function Square(i)
  Square = i*i
End Function

0
投票

您可以将所有脚本转换为头脚本并通过此代码导入:

' Features:
'   * Builtin of inclusion guard
'   * Inclusion path can be relative to the script directory
Class ImportFunction
    Private imports_dict_obj_
    Private fs_obj_

    Private Sub CLASS_INITIALIZE
        set imports_dict_obj_ = WScript.createObject("Scripting.Dictionary")
        set fs_obj_ = WScript.createObject("Scripting.FileSystemObject")
    End Sub

    Public Default Property Get func(file_path_str)
        If "/" = Left(file_path_str, 1) Then
            ' is relative to the script directory
            script_file_path_str = WScript.ScriptFullName
            Dim script_file_obj : Set script_file_obj = fs_obj_.GetFile(script_file_path_str)
            file_path_str = fs_obj_.GetParentFolderName(script_file_obj) & file_path_str
        End If
        file_path_str = fs_obj_.GetAbsolutePathName(file_path_str)

        If Not imports_dict_obj_.Exists(file_path_str) Then
            ExecuteGlobal fs_obj_.OpenTextFile(file_path_str).ReadAll()
            imports_dict_obj_.Add file_path_str, Null
        End If
    End Property
End Class

Dim Import : Set Import = New ImportFunction

Import("/mylib.vbs")

MyLibFoo

优点

  • 用作包含防护存储的全局字典。

缺点

  • Windows 10+ 可以将
    ExecuteGlobal
    调用视为恶意软件活动并阻止它。然后,您必须明确允许包含
    ExecuteGlobal
    调用的每个脚本。
© www.soinside.com 2019 - 2024. All rights reserved.