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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With