Wscript.Echo で止めない為に
WSH のテストをする場合エクスプローラからの起動が便利なわけですが、GUI を使用するとどうしても Wscript.exe が起動されて、デバッグの為に表示している Wscript.Echo が 実行毎にダイアログ表示になってしまいます。 これでは、ループ内で処理している場合等は悲惨な事になります。 そうならない為の関数です。スクリプト自身から再度 Cscript.exe で実行させる
具体的には Cscript.exe で実行して無かった場合にコマンドプロンプトを開いて、そこから Cscript.exe で自分自身を実行させて、終了したら PAUSE します。( Wscript で実行されたスクリプトは終了させます ) ※ スクリプトへの引数は引継ぎますサンプルコード( .vbs )
▼ 以下のコードでは、Crun 関数がその部分ですが、それを利用して『デスクトップのショートカットのアイコン情報』の一覧を表示しています。
01.
Call
Crun()
02.
03.
Set
Shell = WScript.CreateObject(
"Shell.Application"
)
04.
Set
WshShell = WScript.CreateObject(
"WScript.Shell"
)
05.
06.
' デスクトップ
07.
Set
objFolder = Shell.NameSpace( 0 )
08.
09.
Set
objFolderItems = objFolder.Items()
10.
' 一覧の数
11.
nCount = objFolderItems.Count
12.
13.
' デスクトップ一覧の列挙
14.
For
i = 0 to nCount - 1
15.
16.
strPath = objFolderItems.Item(i).Path
17.
' パスをピリオドで分解
18.
aData = Split( strPath,
"."
)
19.
' 配列の上限値より、一番右端にある拡張子を取得
20.
strTarget = aData( Ubound( aData ) )
21.
' 大文字に変換
22.
strTarget = Ucase( strTarget )
23.
24.
' デスクトップのショートカットのアイコン情報を取得
25.
if strTarget =
"LNK"
then
26.
' ショートカットへのオブジェクト( 保存はしない )
27.
Set
oShellLink = WshShell.CreateShortcut(strPath)
28.
strTarget = oShellLink.IconLocation
29.
' %変数名% で参照される環境変数を展開する
30.
strTarget = WshShell.ExpandEnvironmentStrings(strTarget)
31.
if strTarget =
",0"
then
32.
' アイコンは、TargetPath の 0 番目のアイコンを使用
33.
Wscript.Echo oShellLink.TargetPath
34.
else
35.
' アイコンは、strTarget を , で分解して抽出
36.
Wscript.Echo strTarget
37.
end if
38.
end if
39.
40.
Next
41.
42.
' **********************************************************
43.
' Cscript.exe で実行を強制
44.
' Cscript.exe の実行終了後 pause で一時停止
45.
' **********************************************************
46.
Function
Crun( )
47.
48.
Dim
str,WshShell
49.
50.
' 実行中の WSH のフルパス
51.
str = WScript.FullName
52.
' 右から11文字取得
53.
str = Right( str, 11 )
54.
' 全て大文字に変更
55.
str = Ucase( str )
56.
' CSCRIPT.EXE でなければ処理を行う
57.
if str <>
"CSCRIPT.EXE"
then
58.
' 実行中の自分自身(スクリプト)のフルパスを取得
59.
str = WScript.ScriptFullName
60.
61.
Set
WshShell = CreateObject(
"WScript.Shell"
)
62.
63.
' 実行中の自分自身(スクリプト)への引数を引き継ぐ為の文字列を作成
64.
strParam =
" "
65.
For
I = 0 to Wscript.Arguments.Count - 1
66.
if instr(Wscript.Arguments(I),
" "
) < 1 then
67.
strParam = strParam & Wscript.Arguments(I) &
" "
68.
else
69.
strParam = strParam & Dd(Wscript.Arguments(I)) &
" "
70.
end if
71.
Next
72.
' cscript.exe で実行しなおす為のコマンドラインを実行
73.
Call
WshShell.Run(
"cmd.exe /c cscript.exe "
& Dd(str) & strParam &
" & pause"
, 1 )
74.
' 実行中の自分自身(スクリプト)を終了
75.
WScript.Quit
76.
end if
77.
78.
End
Function
79.
' **********************************************************
80.
' 文字列を " で囲む関数
81.
' **********************************************************
82.
Function
Dd( strValue )
83.
84.
Dd =
""
""
& strValue &
""
""
85.
86.
End
function
Microsoft のドキュメント
Shell.NameSpace method ShellSpecialFolderConstants(0はデスクトップ) Folder.Items method CreateShortcut メソッド ExpandEnvironmentStrings メソッド WshShortcut オブジェクト のプロパティ