Tips - WSH

【TOP】

Scripting.Dictionaryオブジェクトを使う
Scripting.Dictionary オブジェクトはその名のとおり、キーとその値をセットとして登録することができます。
Perl などの連想配列に似ています。キーには整数値、文字列が使用できます。
メソッド、プロパティの例を以下に示します。
Option Explicit Dim dic Dim i Set dic = WScript.CreateObject("Scripting.Dictionary") ' Add メソッド dic.Add "Mon", "月曜日" 'Call dic.Add("mon", "月曜日") でもOK. dic.Add "Tue", "火曜日" dic.Add "Wed", "水曜日" dic.Add "Thu", "木曜日" dic.Add "Fri", "金曜日" dic.Add "Sat", "土曜日" dic.Add "Sun", "日曜日" Call printLine() ' Exists メソッド(Function myExistsを参照) WScript.Echo "The key 'wed' is " & myExists("wed") WScript.Echo "The key 'Wed' is " & myExists("Wed") Call printLine() ' Keys メソッド、Count プロパティ Dim myKeys myKeys = dic.Keys() For i=0 To dic.Count-1 WScript.Echo myKeys(i) Next Call printLine() ' Items メソッド Dim myItems myItems = dic.Items() For i=0 To dic.Count-1 WScript.Echo myItems(i) Next Call printLine() ' Remove メソッド WScript.Echo dic.Exists("Sat") dic.Remove("Sat") WScript.Echo dic.Exists("Sat") Call printLine() ' Item プロパティ WScript.Echo dic.Item("Mon") 'WScript.Echo dic("mon") でもOK. Call printLine() ' Key プロパティ dic.Key("Mon") = "monkey" 'キーを変更 dic.Key("monkey") = "Mon" '元に戻しとこう。 ' RemoveAll メソッド WScript.Echo "Count=" & dic.Count dic.RemoveAll WScript.Echo "Count=" & dic.Count Set dic = Nothing Function myExists(key) If dic.Exists(key) Then myExists = "exists." Else myExists = "not exitsts." End If End Function Sub printLine() WScript.Echo "---------------------------------" End Sub
上記のコードを CScript.exe で実行した結果を以下に示します。
C:\WSH>cscript //nologo C:\WSH\Scripting.Dictionary.vbs --------------------------------- The key 'wed' is not exitsts. The key 'Wed' is exists. --------------------------------- Mon Tue Wed Thu Fri Sat Sun --------------------------------- 月曜日 火曜日 水曜日 木曜日 金曜日 土曜日 日曜日 --------------------------------- -1 0 --------------------------------- 月曜日 --------------------------------- Count=6 Count=0 C:\WSH>
【戻る】