WMI の典型的なイベント監視のサンプルです。 ( リンク先は、Microsoft の TechNet のスクリプト センターです ) ファイル作成の監視1) C:\scripts フォルダを作成します。 2) 適当な場所にスクリプトを作成します(file_create.vbs) 3) そのフォルダをエクスプローラでSHIFTキーを押しながら右クリックしてコマンドブロンプトを開きます 4) cscript file_create.vbs と実行します 5) C:\scripts でファイルを作成します
strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\cimv2") Set colMonitoredEvents = objWMIService.ExecNotificationQuery _ ("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _ & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _ & "TargetInstance.GroupComponent= " _ & "'Win32_Directory.Name=""c:\\\\scripts""'") Do Set objLatestEvent = colMonitoredEvents.NextEvent Wscript.Echo objLatestEvent.TargetInstance.PartComponent Loop
ファイル変更の監視
strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\cimv2") Set colMonitoredEvents = objWMIService.ExecNotificationQuery _ ("SELECT * FROM __InstanceModificationEvent WITHIN 10 WHERE " _ & "TargetInstance ISA 'CIM_DataFile' and " _ & "TargetInstance.Name='c:\\scripts\\index.vbs'") Do Set objLatestEvent = colMonitoredEvents.NextEvent Wscript.Echo "File: " & objLatestEvent.TargetInstance.Name Wscript.Echo "New size: " & objLatestEvent.TargetInstance.FileSize Wscript.Echo "Old size: " & objLatestEvent.PreviousInstance.FileSize Loop
ファイル削除の監視
strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\cimv2") Set colMonitoredEvents = objWMIService.ExecNotificationQuery _ ("SELECT * FROM __InstanceDeletionEvent WITHIN 10 WHERE " _ & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _ & "TargetInstance.GroupComponent= " _ & "'Win32_Directory.Name=""c:\\\\scripts""'") Do Set objLatestEvent = colMonitoredEvents.NextEvent Wscript.Echo objLatestEvent.TargetInstance.PartComponent Loop
利用できるディスク領域の監視
Const LOCAL_HARD_DISK = 3 strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colMonitoredDisks = objWMIService.ExecNotificationQuery _ ("Select * from __instancemodificationevent within 30 where " _ & "TargetInstance isa 'Win32_LogicalDisk'") Do Set objDiskChange = colMonitoredDisks.NextEvent If objDiskChange.TargetInstance.DriveType = LOCAL_HARD_DISK Then If objDiskChange.TargetInstance.Size < 100000000 Then Wscript.Echo "Hard disk space is below 100000000 bytes." End If End If Loop
【VBScript関連のカテゴリ】