ラブびあ

ビール。ときどきラブ

WOWで動かすテンプレ

64bit環境で32bitCOMを使うためのテンプレ。64bit環境でWOWじゃなかったらWOWで自分自身を起動しなおします。template.vbsのinit、main、fini、に適宜処理を記述します。cmd.vbs、wow64.vbsはincludeするので同じフォルダに置いてください。

template.vbs

option explicit
dim wsh,fso
const ForReading   = 1
const ForWriting   = 2
const ForAppending = 8
set wsh = CreateObject("WScript.Shell")
set fso = CreateObject("Scripting.FileSystemObject")

include "cmd.vbs"
include "wow64.vbs"

call init
call main
call fini

set wsh = nothing
set fso = nothing

WScript.Quit '-----------------------------------------------------------------

sub init()
end sub

sub main()
	dim i
	for i = 0 to WScript.Arguments.Count - 1
		call func(WScript.Arguments(i))
	next
end sub

sub func(arg)
end sub

sub fini()
end sub

sub include(filename)
	filename = fso.BuildPath(fso.GetParentFolderName(WScript.ScriptFullName), filename)
	ExecuteGlobal fso.OpenTextFile(filename, ForReading, False).ReadAll()
end sub

cmd.vbs

'パラメータを展開する

' コレクションの各要素を結合する
' msgbox cmd(WScript.Arguments)

' 文字列の各要素を展開する ※各要素はグローバルで定義する
' A = "hoge.exe"
' B = "arg1"
' C = "arg2"
' msgbox cmd("[A] [B] [C]")

function cmd(v)
	if IsObject(v) then
		dim i, arr
		redim arr(v.Count-1)
		for i = 0 to v.Count - 1
			arr(i) = quote(v(i))
		next
		cmd = join(arr)
	else
		cmd = v
		with CreateObject("VBScript.RegExp")
			.Pattern = "(\[.*?\])"
			.Global = True
			do while .Test(cmd)
				dim par
				for each par in .Execute(cmd)
					Execute "cmd = Replace(cmd, par, quote(" & par.subMatches(0) & "))"
				next
			loop
		end with
	end if
end function

function quote(s)
	quote = """" & Replace(s, """", """""") & """"
end function

wow64.vbs

call wow64
sub wow64
	'64bit環境か?
	if strcomp("AMD64", wsh.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%"), 1) <> 0 then
		exit sub
	end if

	dim wow64_engine ' C:\Windows\SysWOW64\xscript.exe
	wow64_engine = _
		fso.BuildPath( _
		fso.BuildPath( _
			wsh.ExpandEnvironmentStrings("%windir%"), "SysWOW64"), _
			fso.GetFileName(WScript.FullName))

	'wow64で実行しているか?
	if strcomp(wow64_engine, WScript.Fullname, 1) = 0 then
		exit sub
	end if

	'wow64で実行できるか?
	if not fso.FileExists(wow64_engine) then
		exit sub
	end if

	'wow64で起動しなおす
	wsh.Run quote(wow64_engine) & " " & quote(WScript.ScriptFullName) & " " & cmd(WScript.Arguments)

	WScript.Quit
end sub