VB.NET 中的 WScript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9590211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:59:25  来源:igfitidea点击:

WScript in VB.NET?

vb.netvbscriptwsh

提问by user1196604

This is a snipet of code from my program:

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

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

But for some reason, "WScript" is not declared. I know that this code works in VBScript but i'm trying to get it to work with vb.net. Whats going wrong?

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

回答by Helen

The WScriptobject is specific to Windows Script Host and doesn't exist in .NET Framework.

WScript对象特定于 Windows Script Host,在 .NET Framework 中不存在。

Actually, all of the WScript.Shellobject functionality is available in .NET Framework classes. So if you're porting VBScript code to VB.NET, you should rewrite it using .NET classes rather than using Windows Script Host COM objects.

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


If, for some reason, you prefer to use COM objects anyway, you need to add the appropriate COM library references to your project in order to have these objects available to your application. In case of WScript.Shell, it's %WinDir%\System32\wshom.ocx(or %WinDir%\SysWOW64\wshom.ocxon 64-bit Windows). Then you can write code like this:


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

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


Alternatively, you can create instances of COM objects using


或者,您可以使用创建 COM 对象的实例

Activator.CreateInstance(Type.GetTypeFromProgID(ProgID))

and then work with them using late binding. Like this, for example*:

然后使用后期绑定与他们合作。像这样,例如*

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

* I don't know VB.NET well, so this code may be ugly; feel free to improve.

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