vb.net - VB.NET 中的 WScript?

标签 vb.net vbscript wsh

这是我程序中的一段代码:

WSHShell = WScript.CreateObject("WScript.Shell")

但是由于某种原因,没有声明“WScript”。我知道这段代码在 VBScript 中工作,但我正试图让它与 vb.net 一起工作。怎么了?

最佳答案

WScript对象特定于 Windows 脚本宿主,在 .NET Framework 中不存在。

实际上,所有 WScript.Shell .NET Framework 类中提供了对象功能。因此,如果您将 VBScript 代码移植到 VB.NET,您应该使用 .NET 类而不是使用 Windows Script Host COM 对象来重写它。

如果出于某种原因,您更喜欢使用 COM 对象,则需要将适当的 COM 库引用添加到您的项目中,以使这些对象可用于您的应用程序。如果是 WScript.Shell ,它是 %WinDir%\System32\wshom.ocx(或 %WinDir%\SysWOW64\wshom.ocx 在 64 位 Windows 上)。然后你可以写这样的代码:

Imports IWshRuntimeLibrary
....
Dim shell As WshShell = New WshShell
MsgBox(shell.ExpandEnvironmentStrings("%windir%"))

或者,您可以使用创建 COM 对象的实例
Activator.CreateInstance(Type.GetTypeFromProgID(ProgID))

然后使用后期绑定(bind)与他们合作。像这样,例如*:
Imports System.Reflection
Imports System.Runtime.InteropServices
...

Dim shell As Object = Nothing

Dim wshtype As Type = Type.GetTypeFromProgID("WScript.Shell")
If Not wshtype Is Nothing Then
    shell = Activator.CreateInstance(wshtype)
End If

If Not shell Is Nothing Then
    Dim str As String = CStr(wshtype.InvokeMember(
        "ExpandEnvironmentStrings",
        BindingFlags.InvokeMethod,
        Nothing,
        shell,
        {"%windir%"}
    ))
    MsgBox(str)

    ' Do something else

    Marshal.ReleaseComObject(shell)
End If

* 我不太了解VB.NET,所以这段代码可能很难看;随时改进。

关于vb.net - VB.NET 中的 WScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590211/

相关文章:

vb.net - VB.NET 中 typedef 的等效项或解决方法是什么?

vbscript - 在 VBScript 中检索 Cookie 和发送 Cookie 和发布变量

wsh - 如何在没有两个 if 语句的情况下检查 wscript.arguments(0) 的值

c# - VB.NET 中存在的 C# 中的 Winforms "application framework"在哪里?

vb.net - GlovePIE 和应用程序之间的通信

.net - 通过引用传递数组元素

powershell - 从 "other people"证书存储中删除证书

vbscript - VB GoTo编译失败

javascript - 如何使用 JScript 触摸文件?

javascript - 为什么这个基本的 Meteor 创建项目命令失败了?