VBScript : InternetExplorer.Application で、ファイルを開くダイアログを開く

管理者権限で実行する必要がある

昔から一般的に使われて来た方法ですが、ある時から about:blank では、fakepath というパスで返るようになって使えなくなっていました。そこで、ローカルにファイルを作ってそれで対処しています。但し、管理者権限で実行する必要があるので冒頭の処理が必要です。

簡易的な【ファイルを開くダイアログ】

ファイルの種類は設定できません。どうしても VBScript でファイルを開く為のダイアログを正しく使いたい場合は、COM を作成して呼び出す必要があります( exe に実行させて、ファイルで引き渡すと言う手もあります )。しかし、本来 VBScript で行う処理は簡易的なものなのでそこまでこだわる必要も無いのでこれで十分使えると思います。 冒頭の objShell.MinimizeAll は実行しておかないと、エクスプローラから実行した場合その下にファイルを開くダイアログが隠れてしまいます。 このソースは拡張子が .wsf 用です。
01.<JOB>
02.<SCRIPT language="VBScript">
03.' ************************************************
04.' 管理者として実行を強制する
05.' ************************************************
06.Set objShell = Wscript.CreateObject("Shell.Application")
07.if Wscript.Arguments.Count = 0 then
08.        objShell.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
09.        Wscript.Quit
10.end if
11. 
12.' ************************************************
13.' ファイルを開くダイアログの為に他を全て最小化する
14.' ************************************************
15.objShell.MinimizeAll
16. 
17.' ************************************************
18.' ファイル選択
19.' ************************************************
20.strValue = OpenLocalFileName
21.if strValue = "" then
22.        Wscript.Quit
23.end if
24. 
25.MsgBox( strValue )
26. 
27.' ************************************************
28.' InternetExplorer.Application でファイル選択
29.' ************************************************
30.Function OpenLocalFileName( )
31. 
32.        ' ファイルシステムを操作するオブジェクト
33.        Set Fso = WScript.CreateObject( "Scripting.FileSystemObject" )
34.        ' テンポラリフォルダ
35.        TempDir =  Fso.GetSpecialFolder(2)
36.        on error resume next
37.        ' テンポラリフォルダに空の "local.htm" を作成
38.        Set objHandle = Fso.CreateTextFile( TempDir & "\local.htm", True, True )
39.        if Err.Number <> 0 then
40.                Exit Function
41.        end if
42.        objHandle.Close
43.        on error goto 0
44. 
45.        Set IEDocument = Wscript.CreateObject("InternetExplorer.Application")
46.        IEDocument.Navigate( TempDir & "\local.htm" )
47.        Do While IEDocument.Busy
48.                ' 100 ミリ秒
49.                Wscript.Sleep 100
50.        Loop
51.        IEDocument.document.getElementsByTagName("BODY")(0).innerHTML = "<input id='FilePath' type='file'>"
52.        call IEDocument.document.getElementById("FilePath").click()
53.        if IEDocument.document.getElementById("FilePath").value = "" then
54.                OpenLocalFileName = ""
55.                IEDocument.Quit
56.                Set IEDocument = Nothing
57.                Exit Function
58.        end if
59. 
60.        OpenLocalFileName = IEDocument.document.getElementById("FilePath").value
61. 
62.        IEDocument.Quit
63.        Set IEDocument = Nothing
64. 
65.End Function
66.</SCRIPT>
67.</JOB>