64位系统VBS调用32位COM组件
今天有人问我,为什么他的VBS脚本在64位Windows 7中用VbsEdit可以直接执行,但是直接双击就会出错:ActiveX 部件不能创建对象: ‘MSWinsock.Winsock’。
在64位系统中存在两组不同的wscript.exe和cscript.exe,一组是64位的,在C:\Windows\System32文件夹;一组是32位的,在C:\Windows\SysWOW64文件夹。由于64位和32位的内存模式不同,64位进程无法加载32位DLL,故以DLL封装COM组件无法在64位进程调用。
具体到上面的问题,MSWinsock.Winsock是32位COM组件,而直接双击运行VBS文件默认是以C:\Windows\System32\wscript.exe为宿主的,也就是64位的进程,64位进程无法加载32位的DLL,所以会出现“ActiveX 部件不能创建对象”的错误。如果想不报错的话需要手动指定用32位的宿主来执行。
那为什么用VbsEdit可以直接执行呢?因为早期版本的VbsEdit在64位系统上会自动调用32位的wscript.exe或者cscript.exe来执行脚本。对于比较新的VbsEdit,已经区分为32位的VbsEdit何64位的VbsEdit,不同版本的VbsEdit会调用对应版本的wscript.exe或者cscript.exe来执行。
怎样才能在64位系统里直接双击运行包含32位COM组件调用的VBS脚本呢?一种方法是改注册表,但是这个方法不通用;另一种方法是在VBS代码中做检测:
Option Explicit
Run32()
Dim Winsock
Set Winsock = CreateObject("MSWinsock.Winsock")
MsgBox "成功创建MSWinsock.Winsock对象"
Sub Run32()
'Author: Demon
'Date: 2015/7/9
'Website: http://demon.tw
Dim strComputer, objWMIService, colItems, objItem, strSystemType
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
For Each objItem in colItems
strSystemType = objItem.SystemType
Next
If InStr(strSystemType, "x64") > 0 Then
Dim fso, WshShell, strFullName
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
strFullName = WScript.FullName
If InStr(1, strFullName, "system32", 1) > 0 Then
strFullName = Replace(strFullName, "system32", "SysWOW64", 1, 1, 1)
WshShell.Run strFullName & " " &_
"""" & WScript.ScriptFullName & """", 10, False
WScript.Quit
End If
End If
End Sub