Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WScript in VB.NET?

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?

like image 972
user1196604 Avatar asked Mar 06 '12 19:03

user1196604


People also ask

What is WScript object?

The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file.

What does WScript shell do?

Basically, in the case of wscript. shell, it creates an object that is an instance of the windows shell allowing you to run commands against the windows shell from within your VBScript.


1 Answers

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

Actually, all of the WScript.Shell object 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.


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.ocx on 64-bit Windows). Then you can write code like this:

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


Alternatively, you can create instances of COM objects using

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.

like image 51
Helen Avatar answered Sep 23 '22 07:09

Helen