VBScript( Jscript ) を『管理者として実行する』には、Shell の runas ( 右クリックメニューの実行と同等 ) で実現

VBScript を『管理者として実行する』には、以下の内容ををスクリプトの先頭に記述します

🔻 VBScript

1.Set obj = Wscript.CreateObject("Shell.Application")
2.if Wscript.Arguments.Count = 0 then
3.        obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
4.        Wscript.Quit
5.end if
6. 
7.Wscript.Echo "ここは管理者権限で実行されます"

🔻 Jscript

※ Jscript は WScript 等、大文字小文字の区別があるので注意です。
1.var obj = new ActiveXObject("Shell.Application");
2.if ( WScript.Arguments.length == 0 ) {
3.        obj.ShellExecute( "wscript.exe", WScript.ScriptFullName + " runas", "", "runas", 1 );
4.        WScript.Quit();
5.}
6. 
7.WScript.Echo( "ここは管理者権限で実行されます" );

Shell.ShellExecute method

これは、VBScript から利用可能な Shell の機能を使って、右クリックメニューにある『管理者として実行』を実行する方法です。ここでは日本語では無く runas と言う文字列を使って管理者として実行させています。

但し、引数がなかった場合の処理としては処理終了します。ですからこのスクリプトでは、引数をダミーで一つセットして( この場合一つめの runas がそうです )自分自身を再度呼び出しています。

つまり、Windows からすれば二度目の実行が管理者としての実行になります。

この場合は、スクリプトに引数を渡す事ができません。もし渡したい場合は、違ったトリックを使う必要があるのに注意して下さい。(その場合は、外部ファイルから入力するのがもっとも簡単で確実だと思います)




VBScript, 記録

コマンドプロンプトを『管理者権限』で実行する 8つの方法

Windowsキー + X のメニューから

タスクバーの左端を右クリックして表示されるメニューです。『コマンドプロンプト(管理者)』を使う事が可能です、無い場合は設定変更で表示できます。 【PowerShell を コマンドプロンプトに変更 ※説明あり

Windowsキー + S の検索から

cmd と入力して CTRL+SHIFT+Enter で管理者権限でコマンドプロンプトを表示できます

タスクマネージャーから

ファイルメニューより、新しいタスクの実行を選択する事で、管理者権限を付与してプログラムを実行できます

Windowsキー + R で cmd を実行してから

タスクバーに表示されている『コマンドプロンプト』を、CTRL+SHIFT を押しながらクリックします

ショートカット を作成してから

ショートカット作成時に cmd と入力すると参照後のショートカットが作成されます。そのショートカットを右クリックして『管理者として実行』を選択します。また、ショートカットタブの詳細設定より、『管理者として実行』をチェックしておくと常に管理者として実行できるようになります

VBScript を使う

バッチファイル を使う

結局先ほどの VBScript のコードですが、バッチファイルにそれを作らして実行する事ができるので .bat として用意できます
1.@echo off
2.echo Set obj = CreateObject("Shell.Application"):obj.ShellExecute "cmd.exe", "", "", "runas", 1 > %TEMP%\_acmd.vbs
3.cscript %TEMP%\_acmd.vbs

PowerShell を使う

PowerShell そのものはいろいろ説明が面倒ですが、PowerShell を実行する時のオプションとして考えてもらうのが簡単です( エイリアスとかもありますけれど )

-windowstyle と -command は powershell のオプションで、start は powershell の内部コマンドである Start-Process のエイリアスで、-verb は start のオプションです

この場合、-windowstyle hidden はあっても無くてもあまり変わらないと思います。


JScript / VBScript : 指定したフォルダ内のフォルダ毎の使用済みサイズを読める範囲でレポートする

▼ JScript のダウンロード

▼ VBScript のダウンロード

System Volume Information は、無駄に使われてる場合が多いそうです。( 今日 5G 削除しました ) ✅ 参考ページ

show-folders-size.js

001.// ************************************************
002.// カンマ編集
003.// ************************************************
004.String.prototype.number_format =
005.function (prefix) {
006.        var num = this.valueOf();
007.        prefix = prefix || '';
008.        num += '';
009.        var splitStr = num.split('.');
010.        var splitLeft = splitStr[0];
011.        var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
012.        var regx = /(\d+)(\d{3})/;
013.        while (regx.test(splitLeft)) {
014.                splitLeft = splitLeft.replace(regx, '$1' + ',' + '$2');
015.        }
016.        return prefix + splitLeft + splitRight;
017.}
018. 
019.// ************************************************
020.// オブジェクト
021.// ************************************************
022.var Shell = new ActiveXObject("Shell.Application");
023.var WshShell = new ActiveXObject("WScript.Shell");
024.var Fso = new ActiveXObject( "Scripting.FileSystemObject" );
025. 
026.// ************************************************
027.// 管理者権限のコマンドプロンプトで再実行
028.// ************************************************
029.if ( WScript.Arguments.length == 0 ) {
030.        Shell.ShellExecute( "cmd.exe", "/c cscript.exe " + Dd(WScript.ScriptFullName) + " next" + " & pause", "", "runas", 1 );
031.        WScript.Quit();
032.}
033. 
034. 
035.var target = SelectDir( "対象フォルダを選択して下さい" )
036.if ( target == "" ) {
037.        WScript.Quit();
038.}
039. 
040.WScript.Echo( target )
041. 
042.// ************************************************
043.// フォルダオブジェクト取得
044.// ************************************************
045.var objFolder =  Fso.GetFolder(target)
046. 
047.var folderCollection = new Enumerator(objFolder.SubFolders);
048. 
049.var TargetSize = 0;
050.var obj;
051.var num;
052.var line;
053.for ( ;!folderCollection.atEnd(); folderCollection.moveNext()) {
054. 
055.        obj = folderCollection.item();
056.         
057.        try {
058.                num = Math.floor(obj.Size / 1024) / 1024;
059.                num = Math.floor( num * 1000 ) / 1000
060.                line = Lpad(("" + num).number_format()," ", 15) + " M : " + obj.Name
061.                WScript.Echo( line );
062. 
063.                // フォルダ全体の合計
064.                TargetSize = TargetSize + obj.Size
065.        }
066.        catch(e) {
067.                WScript.Echo( obj.Name + " : 処理できません");
068.        }
069. 
070.}
071. 
072.WScript.Echo( "" );
073. 
074.num = Math.floor(TargetSize / 1024) / 1024;
075.num = Math.floor( num * 1000 ) / 1000
076.line = Lpad(("" + num).number_format()," ", 15) + " M : " + "表示合計"
077.WScript.Echo( line );
078. 
079.// ************************************************
080.// ディレクトリ選択
081.// ************************************************
082.function SelectDir( strTitle ) {
083. 
084.        var obj
085. 
086.        obj = Shell.BrowseForFolder( 0, strTitle, 0x4B, 0 )
087.        if ( obj == null ) {
088.                return "";
089.        }
090.        if ( !obj.Self.IsFileSystem ) {
091.                ErrorMessage = "ファイルシステムではありません";
092.                return "";
093.        }
094. 
095.        return obj.Self.Path;
096. 
097.}
098. 
099.// ************************************************
100.// ダブルクォートで囲む
101.// ************************************************
102.function Dd( strValue ) {
103. 
104.        return "\"" + strValue + "\""
105. 
106.}
107. 
108.// ************************************************
109.// 指定数、指定文字列左側を埋める
110.// ※少数以下3桁の調整
111.// ************************************************
112.function Lpad( strValue, str, nLen ) {
113. 
114.        var i;
115.        var wk = "";
116. 
117.        for( i = 0; i < nLen; i++ ) {
118.                wk += str;
119.        }
120.         
121.        var test = strValue.split(".");
122.        if ( test.length == 2 ) {
123.                if ( test[1].length == 0 ) {
124.                        strValue += "000"
125.                }
126.                if ( test[1].length == 1 ) {
127.                        strValue += "00"
128.                }
129.                if ( test[1].length == 2 ) {
130.                        strValue += "0"
131.                }
132.        }
133.        else {
134.                strValue += ".000"
135.        }
136. 
137.        return ( wk + strValue ).slice( nLen * -1 );
138. 
139.}


show-folders-size.vbs

001.' ************************************************
002.' 管理者権限で実行用
003.' ************************************************
004.Set Shell = CreateObject( "Shell.Application" )
005. 
006.' ************************************************
007.' 管理者権限で再実行
008.' ************************************************
009.if Wscript.Arguments.Count = 0 then
010.        Shell.ShellExecute "cmd.exe", "/c cscript.exe " & Dd(WScript.ScriptFullName) & " next" & " & pause", "", "runas", 1
011.        Wscript.Quit
012.end if
013. 
014.' ************************************************
015.' 除外フォルダ名を スペースで区切って並べる
016.' (簡易的な除外)
017.' ************************************************
018.Dim Exclude
019.Exclude = ".gem"
020.Exclude = Lcase(Exclude)
021. 
022.' ************************************************
023.' 処理用
024.' ************************************************
025.Set WshShell = CreateObject( "WScript.Shell" )
026.Set Fso = CreateObject( "Scripting.FileSystemObject" )
027. 
028.Dim target
029. 
030.' ************************************************
031.' 対象フォルダを選択
032.' ************************************************
033.target = SelectDir( "対象フォルダを選択して下さい" )
034.if target = "" then
035.        Wscript.Quit
036.end if
037. 
038.Wscript.Echo target
039.Wscript.Echo
040. 
041.' ************************************************
042.' フォルダオブジェクト取得
043.' ************************************************
044.Set objFolder =  Fso.GetFolder(target)
045. 
046.' ************************************************
047.' サブフォルダコレクション取得
048.' ************************************************
049.Set colSubFolder =  objFolder.SubFolders
050. 
051.' ************************************************
052.' 一覧
053.' ************************************************
054.Dim TargetSize : TargetSize = 0
055.For Each obj in colSubFolder
056. 
057.        Do While true
058. 
059.                if InStr(Exclude,Lcase(obj.Name)) > 0 then
060.                        Exit Do
061.                end if
062. 
063.                on error resume next
064.                Wscript.Echo Lpad(FormatNumber((Fix(obj.Size / 1024) / 1024),3)," ", 15) & " M : " & obj.Name
065.                if Err.Number <> 0 then
066.                        Wscript.Echo "                  ( " & obj.Name & " : 処理できません )"
067.                else
068.                        TargetSize = TargetSize + obj.Size
069.                end if
070.                on error goto 0
071. 
072. 
073.                Exit Do
074.        Loop
075. 
076. 
077.Next
078. 
079.Wscript.Echo
080. 
081.Dim AllSize
082.Dim er : er = 0
083.on error resume next
084.AllSize = objFolder.Size
085.if Err.Number <> 0 then
086.        er = 1
087.        AllSize = TargetSize
088.end if
089.on error goto 0
090. 
091. 
092.Wscript.Echo Lpad(FormatNumber((Fix(TargetSize / 1024) / 1024),3)," ", 15) & " M : " & "表示合計"
093. 
094.if er = 1 then
095.        Wscript.Echo "                  ( " & target & " のサイズは取得できませんでした )"
096.else
097.        Wscript.Echo Lpad(FormatNumber((Fix(AllSize / 1024) / 1024),3)," ", 15) & " M : " & target & " のサイズ"
098.end if
099. 
100.Dim fsize : fsize = 0
101.For Each file in objFolder.files
102.        fsize = fsize + file.size
103.Next
104.Wscript.Echo Lpad(FormatNumber((Fix((fsize) / 1024) / 1024),3)," ", 15) & " M : " & target & " 下のファイル"
105. 
106.Wscript.Echo
107. 
108.' ************************************************
109.' ディレクトリ選択
110.' ************************************************
111.Function SelectDir( strTitle )
112. 
113.        Dim obj
114. 
115.        Set obj = Shell.BrowseForFolder( 0, strTitle, &H4B, 0 )
116.        if obj is nothing then
117.                SelectDir = ""
118.                Exit Function
119.        end if
120.        if not obj.Self.IsFileSystem then
121.                ErrorMessage = "ファイルシステムではありません"
122.                SelectDir = ""
123.                Exit Function
124.        end if
125. 
126.        SelectDir = obj.Self.Path
127. 
128.End Function
129. 
130.' ************************************************
131.' ダブルクォートで囲む
132.' ************************************************
133.Function Dd( strValue )
134. 
135.        Dd = """" & strValue & """"
136. 
137.End function
138. 
139.' ************************************************
140.' 指定数、指定文字列左側を埋める
141.' ************************************************
142.Function Lpad( strValue, str, nLen )
143. 
144.        Lpad = Right( String(nLen,str) & strValue, nLen )
145. 
146.End Function




VBScript : WshShell.Runによる 【外部プログラムの実行】 のバリエーション

外部プログラムの実行

VBScript を何の為に使うかという場合、最も一般的に利用価値の高いのは、やはりプログラムの実行です。 わりと簡単に使えるのですが、プログラム(言語)でもあるので、専門知識が無ければ、なかなか難しい部分もあります。しかし、実行だけで言えば、2行で書けるので、その場合に「できること」を知っておくと絶対に得をします。

同期処理(コマンドプロンプトウインドウを開かない)

1.Set WshShell = WScript.CreateObject("WScript.Shell")
2.Call WshShell.Run( "zip.exe -r homepage D:\nifty\homepage", 0, True )


同期処理(コマンドプロンプトウインドウを開く)

1.Set WshShell = WScript.CreateObject("WScript.Shell")
2.Call WshShell.Run( "zip.exe -r homepage D:\nifty\homepage", , True )

非同期処理

Call WshShell.Run( "zip.exe -r homepage D:\nifty\homepage",0 ) でコマンドプロンプトウインドウは開きません
1.Set WshShell = WScript.CreateObject("WScript.Shell")
2.WshShell.Run( "zip.exe -r homepage D:\nifty\homepage" )

関連するページ

WshShell.Run による外部プログラムの実行 :外部プログラムの実行

VBScript : GUID取得

Scriptlet.TypeLib で GUID を取得できます

▼ InternetExplorer.Application でクリップボードへコピーする

01.' GUID 取得用
02.Set TypeLib = CreateObject("Scriptlet.TypeLib")
03. 
04.' クリップボード用
05.' ※ HTA 等では直接 window.clipboardData より実行
06.' ※ するように書き換える必要があります
07.Set objIE = CreateObject("InternetExplorer.Application")
08.objIE.Navigate("about:blank")
09.Do While objIE.Busy
10.        ' 100 ミリ秒
11.        Wscript.Sleep 100
12.Loop
13. 
14.Call objIE.document.parentWindow.clipboardData.SetData( "Text", TypeLib.Guid & "" )
15.objIE.Quit
16. 
17.WScript.Echo "クリップボードにコピーしました" & vbCrLf & vbCrLf & TypeLib.Guid


▼ 自分でクリップボードへコピーする

1.' GUID 取得用
2.Set TypeLib = CreateObject("Scriptlet.TypeLib")
3. 
4.Call InputBox("コピーして使用して下さい","新しい GUID を取得しました",TypeLib.Guid)


▼ コマンドブロンプトを使う( clip.exe )

1.sCommand = "cmd /c echo Set TypeLib=CreateObject(""Scriptlet.TypeLib""):Wscript.echo TypeLib.Guid>%temp%\_.vbs&cscript.exe /NOLOGO %temp%\_.vbs | clip"
2. 
3.Set WshShell = WScript.CreateObject("WScript.Shell")
4.' 同期処理(コマンドプロンプトウインドウを開かない)
5.Call WshShell.Run( sCommand, 0, True )



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>



VBScript( Jscript ) を『管理者として実行する』には、Shell の runas ( 右クリックメニューの実行と同等 ) で実現します

UAC によるセキュリティの影響で VBScript を使う場合、管理者権限で実行しないとレジストリの一部には書き込めるのに重要なフォルダには書き込めないというような OS が決めたルールがあります。

それに対する対処の最も簡単な方法は、以下の内容ををスクリプトの先頭に記述する事です

🔻 VBScript

1.Set obj = Wscript.CreateObject("Shell.Application")
2.if Wscript.Arguments.Count = 0 then
3.        obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
4.        Wscript.Quit
5.end if
6. 
7.Wscript.Echo "ここは管理者権限で実行されます"

🔻 Jscript

※ Jscript は WScript 等、大文字小文字の区別があるので注意です。 ※ ダウンロードは、拡張子 .htm で SHIFT_JIS ですので、利用時は .js に変更してお使い下さい。
1.var obj = new ActiveXObject("Shell.Application");
2.if ( WScript.Arguments.length == 0 ) {
3.        obj.ShellExecute( "wscript.exe", WScript.ScriptFullName + " runas", "", "runas", 1 );
4.        WScript.Quit();
5.}
6. 
7.WScript.Echo( "ここは管理者権限で実行されます" );

Shell.ShellExecute method

これは、VBScript から利用可能な Shell の機能を使って、右クリックメニューにある『管理者として実行』を実行する方法です。ここでは日本語では無く runas と言う文字列を使って管理者として実行させています。

但し、引数がなかった場合の処理としては処理終了します。ですからこのスクリプトでは、引数をダミーで一つセットして( この場合一つめの runas がそうです )自分自身を再度呼び出しています。

つまり、Windows からすれば二度目の実行が管理者としての実行になります。

この場合は、スクリプトに引数を渡す事ができません。もし渡したいしたい場合は、違ったトリックを使う必要があるのに注意して下さい。(その場合は、外部ファイルから入力するのがもっとも簡単で確実だと思います)




ADODB.Recordset を使用したメモリソート

Rs.Sort = "ソートキー,ソートデータ DESC"

VBScript だけではソートができないので、ADODB.Recordset を使用しています。ここでは、二つのフィールドを使って( SQL の構文で ) ソートしています。
01.' Null で終了する Unicode 文字列を示します (DBTYPE_WSTR)。
02.Const adWChar = 130
03. 
04.Dim Rs
05.Dim strResult
06. 
07.Set Rs = CreateObject("ADODB.Recordset")
08.Rs.Fields.Append "ソートキー", adWChar,128
09.Rs.Fields.Append "ソートデータ", adWChar,128
10.Rs.Open
11. 
12.Rs.AddNew
13.Rs.Fields("ソートキー").value = "C"
14.Rs.Fields("ソートデータ").value = "山田1"
15. 
16.Rs.AddNew
17.Rs.Fields("ソートキー").value = "C"
18.Rs.Fields("ソートデータ").value = "山田2"
19. 
20.Rs.AddNew
21.Rs.Fields("ソートキー").value = "A"
22.Rs.Fields("ソートデータ").value = "田中"
23. 
24.Rs.AddNew
25.Rs.Fields("ソートキー").value = "B"
26.Rs.Fields("ソートデータ").value = "鈴木"
27. 
28. 
29.' ****************************
30.' 順ソート + 逆ソート
31.' ****************************
32.Rs.Sort = "ソートキー,ソートデータ DESC"
33. 
34.' ****************************
35.' 先頭に移動
36.' ****************************
37.Rs.MoveFirst
38. 
39.strResult = ""
40.Do while not Rs.EOF
41. 
42.        strResult = strResult & Rs.Fields("ソートキー").Value & " : "
43.        strResult = strResult & Rs.Fields("ソートデータ").Value & vbCrLf
44. 
45.        Rs.MoveNext
46. 
47.Loop
48. 
49.' ****************************
50.' 順ソート結果を表示
51.' ****************************
52.Wscript.Echo strResult
53. 
54.' ****************************
55.' 逆ソート + 順ソート
56.' ****************************
57.Rs.Sort = "ソートキー DESC,ソートデータ"
58. 
59.' ****************************
60.' 先頭に移動
61.' ****************************
62.Rs.MoveFirst
63. 
64.strResult = ""
65.Do while not Rs.EOF
66. 
67.        strResult = strResult & Rs.Fields("ソートキー").Value & " : "
68.        strResult = strResult & Rs.Fields("ソートデータ").Value & vbCrLf
69. 
70.        Rs.MoveNext
71. 
72.Loop
73. 
74.' ****************************
75.' 逆ソート結果を表示
76.' ****************************
77.Wscript.Echo strResult
78. 
79.Rs.Close




VBScript : Cscript.exe で実行を強制する為の関数( Function Crun ) : Wscript.Echo で止まらないように

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 オブジェクト のプロパティ

VBScriptの関数定義をWEB上に置いて、Msxml2.ServerXMLHTTP で読みだして PCで使用する

VBScriptの関数定義をWEB上に置いて、PCで使用する の発展版です。
※ WEB 上に置くソースコードは、上記リンク先を参照して下さい。

Msxml2.ServerXMLHTTP で読み出すコードの作成方法

Msxml2.ServerXMLHTTP は昔はバグがありましたが、今はとても優秀なオブジェクトです。ただ、相手側が静的ファイルの場合は UTF-8 扱いになるはずなので、PHP 側でキャラクタセットを明示しています。( 以下のサンプルの PHP / https://toolbox.winofsql.jp/vbs/regtrim.php は SHIFT_JIS です )
01.REM **********************************************************
02.REM 正規表現のトリム
03.REM **********************************************************
04.Function RegTrim( strValue )
05. 
06.        Dim regEx, str
07. 
08.        Set regEx = New RegExp
09.        regEx.IgnoreCase = True
10.        regEx.Pattern = "^[ \s]+"
11.        str = regEx.Replace( strValue, "" )
12.        regEx.Pattern = "[ \s]+$"
13.        RegTrim = regEx.Replace( str, "" )
14. 
15.End Function

このコードを regtrim.vbs や regtrim.txt としてWEB上のどこかに置く場合は、UTF8N で保存します


ExecuteGlobal による動的な関数の登録

読みだした後、ExecuteGlobal で文字列を実行してしまうのが特徴です。Global スコープで実行されるため、最初から定義していたのと同じ事になります。 但し、この処理を行う為に読みだされるソースコード側で注意する事があります 1) コメントにシングルクォートを使わないで REM を使う 2) 条件文で = を使わないで <> の else で表現する これらは、ExecuteGlobal が正しく VBScript の構文を解析する為に重要な準備事項になるので注意して下さい
01.<job>
02.<object id="http" progid="Msxml2.ServerXMLHTTP" />
03.<script language="VBScript">
04. 
05.' 関数のソースコードを読みだして、関数として定義
06.strResult = HTTPGet( "https://toolbox.winofsql.jp/vbs/regtrim.php" )
07.if not IsEmpty( strResult ) and Left( strResult, 3 ) = "REM" then
08.        ' 関数定義の実行
09.        ExecuteGlobal strResult
10.else
11.        MsgBox( "処理できませんでした" )
12.        Wscript.Quit
13.end if
14. 
15.str = RegTrim( getResource( "mydata" ) )
16.MsgBox( "/" & str & "/" )
17. 
18.Function HTTPGet( strUrl )
19. 
20.        on error resume next
21.        Call http.Open("GET", strUrl, False )
22.        if Err.Number <> 0 then
23.                MsgBox(Err.Description)
24.                HTTPGet = Empty
25.                Exit Function
26.        end if
27.        on error goto 0
28. 
29.        Call http.Send()
30. 
31.        HTTPGet = http.responseText
32. 
33.End Function
34.</script>
35.<resource id="mydata">
36. 
37. 
38.    この部分のみ取り出します    
39. 
40. 
41.</resource>
42.</job>