Jump to content
Sign in to follow this  
ptrex

USB drive Monitor Example

Recommended Posts

im my firm, i've created an ADM policy to set NTFS permissions on laptop (domain policy if you prefer)

so when they are @home, they can connect their usb drive... because local policy permits this..

if that gives you a clue :)


-- Arck System _ Soon -- Ideas make everything

"La critique est facile, l'art est difficile"

Projects :

[list] [*]Au3Service : Run your exe as service V3 / Updated 29/07/2013 Get it Here [/list]

Share this post


Link to post
Share on other sites

well, it was (and still is) of course work in progress. One of the other fundamental flaws in the script is the fact that you can plug the USB device prior to script actually running (such as booting up). This would not be picked up by '__InstanceCreationEvent '.

I'm working on an improved script. I've ditched the above WMI query, and instead am using Win32_DiskDrive as the initial check, which will query every 5 seconds for any USB drives (regardless of whether they have been plugged in before the script has started).

As for the AD issue, well this all depends on how you want to control USB devices. My main thought is to prevent users connecting USB devices allowing them to copy data from network servers or try to use software stored on said devices. That subject has many other issues and ways of circumvention, I guess you gotta start somewhere....

so...

1) Do you block ALL USB drives?

2) Do you allow authorised domain/local users to plug in USB devices?

If so, do you query AD or local workstation groups?

3) Do you allow offline connectivity when laptops are not connected to the network?

So far, my latest version is working (it doesn't fall over, or hang when offline). The script now dismounts drives unless it can confirm that the logged on user is a member of a specific AD group. As for how to run the script, that's still up for debate, but I think a service may be the option (I guess this all depends on the environment and situations that the script will be used).

More testing to do.... :)

thanks for the feedback ;)

1) yes

2) my objective is only to allow user that belong to a group to use USB drives

3) laptops should follow the same rules as normal pc's, even in offline mode

I've did my tests as a service and it worked quite well, except when it runs into an error, then the process is still active but it hungs. I would love to see how you avoided those hangs, since until now I could not find a proper way to avoid those COM errors when the network connection changes.


[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

i dont' think that contiuous monitoring is the good solution. My script just block the usb once, and that's it.

i don't think too that you can't have a valuable script with continuous monitoring, security issues :/


-- Arck System _ Soon -- Ideas make everything

"La critique est facile, l'art est difficile"

Projects :

[list] [*]Au3Service : Run your exe as service V3 / Updated 29/07/2013 Get it Here [/list]

Share this post


Link to post
Share on other sites

i dont' think that contiuous monitoring is the good solution. My script just block the usb once, and that's it.

i don't think too that you can't have a valuable script with continuous monitoring, security issues :/

I'm intrigued as to how your script works.


"My God, you're looking hideously ugly today, Ugly Bob."

Share this post


Link to post
Share on other sites

I'm intrigued as to how your script works.

I agree with arcker, that's why I've used this:

Func DisableUSBAccess()
    If FileExists($InfPath & "USBSTOR.INF") Then FileMove($InfPath & "USBSTOR.INF", $InfPath & "USBSTOR.INF_")
    If FileExists($InfPath & "USBSTOR.PNF") Then FileMove($InfPath & "USBSTOR.PNF", $InfPath & "USBSTOR.PNF_")
    RegWrite($RegKeyCheck, "USBAccess", "REG_DWORD", 0)
    RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\", "Start", "REG_DWORD", 4)
EndFunc ;==>DisableUSBAccess

Func EnableUSBAccess()
    If FileExists($InfPath & "USBSTOR.INF_") Then FileMove($InfPath & "USBSTOR.INF_", $InfPath & "USBSTOR.INF")
    If FileExists($InfPath & "USBSTOR.PNF_") Then FileMove($InfPath & "USBSTOR.PNF_", $InfPath & "USBSTOR.PNF")
    RegWrite($RegKeyCheck, "USBAccess", "REG_DWORD", 1)
    RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\", "Start", "REG_DWORD", 3)
EndFunc ;==>EnableUSBAccess

It will only change when the membership of the user changes (ensured by the script running as a service) - even if the script freezes, the access remains the same, and after a reboot it will recheck the access rights.


[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

mmm file move, why not

for me i've a :

runasset("administrator",@computername,"toto")

run("cacls c:\windows\inf\USBSTOR.PNF /g " & @username& ":C")

run("cacls c:\windows\inf\USBSTOR.INF /g " & @username& ":C")

to enable the rights, and to disable, idem by using /d to remove user


-- Arck System _ Soon -- Ideas make everything

"La critique est facile, l'art est difficile"

Projects :

[list] [*]Au3Service : Run your exe as service V3 / Updated 29/07/2013 Get it Here [/list]

Share this post


Link to post
Share on other sites

Here's my latest incarnation...

Tested on a PC and laptop, with the network disabled or cable pulled before and during the script and it remains running, dismounting USB devices.

Additional note, it works when run as the user too, so it could be used to run during logon via Group Policy (this has been tested). Though, there are issues here in that the logged on user could simply kill the process; that's a debate for another time....

CODE

; ====================================================================================================

======================================

; Created by UglyBob - 03/08/2007

; Thanks to:

; Yoan Roblet (Arcker) (AutoIT member) - For the code (functions) which disconnect the detected USB device from the workstation

; ptrex (AutoIT member) - For the initial USB detection code)

; Johny Clelland (AutoIT member) - For the initial AD code to query group membership

; Reference Material -

; http://support.microsoft.com/kb/165721

; Microsoft Script Guy USB Monitor - http://www.microsoft.com/technet/scriptcen...06/hey0213.mspx

; WMI queries - http://msdn2.microsoft.com/en-us/library/aa394173.aspx

; Microsoft Script Guy ID USB Devices - http://www.microsoft.com/technet/scriptcen...05/hey0315.mspx

; Version Control

; ---------------

; Updated - 06/08/2007 - Added filters to the initial SELECT query for USB devices that also create floppy & CD-ROM drives

; Updated - 18/08/2007 - Completely altered the filter, it no longer uses the __InstanceOperationEvent.

; Instead, the Win32_DiskDrive is used to filter on USB connections, then the USBSTOR\ trigger.

; AD is only checked when a device is found, if offline, the device is rejected (this is optional)

; If group is not matched the device is rejected.

; Updated - 20/08/2007 - Added 'objevent' to handle any COM errors when communicating with AD. This prevents the script

; from crashing when the network connection is disrupted.

; ====================================================================================================

======================================

#include <A3LWinApi.au3>

#include <Constants.au3>

; ------------------------------------------------------------------------------------------------------------

; Variables

Dim $AllowUser = False

Dim $Offline = True

Dim $objRootDSE, $OpenVolume, $strDNSDomain, $ADobjErrors

Dim $objWMIService = ObjGet("winmgmts:\\.\root\cimv2")

Dim $szVolumeFormat = "\\\\.\\%s"

Dim $szRootFormat = "%s\\"

Dim $szErrorFormat = "Error %d: %s\n"

Dim $USB_Allow_Group = "GPExempt - USB storage"

;------------------------------------------

;Arbitrary variables

Global Const $INVALID_HANDLE_VALUE = 0

;------------------------------------------

;DeviceIoControl Contants

Global Const $FSCTL_LOCK_VOLUME = int(0x090018)

Global Const $FSCTL_DISMOUNT_VOLUME = int(0x00090020)

Global Const $IOCTL_STORAGE_EJECT_MEDIA = int(0x002D4808)

Global Const $IOCTL_STORAGE_MEDIA_REMOVAL = int(0x002D4804)

;------------------------------------------

;Retry Constants

Global Const $LOCK_TIMEOUT = 10000 ; 10 Seconds

Global Const $LOCK_RETRIES = 3

;------------------------------------------

; AD LDAP variables

Dim $objConnection, $oUsr, $objRootDSE

; ------------------------------------------------------------------------------------------------------------

AutoItSetOption ("TrayIconHide", 1)

$ADobjErrors = ObjEvent("AutoIt.Error", "ADErrors")

While 1

$DeviceQuery = $objWMIService.ExecQuery ( "Select * From Win32_DiskDrive Where (InterfaceType = 'USB' and Size > 0)" )

For $ItemFound in $DeviceQuery

ConsoleWrite ( "Win32_DiskDrive = " & $ItemFound.Size & " - " & $ItemFound.Caption & " - " & $ItemFound.PNPDeviceID & @CRLF)

If StringLeft($ItemFound.PNPDeviceID, 8) = "USBSTOR\" Then

If Check_AD_Link($Offline) = False Then

If Memberof($AllowUser) = False Then

ConsoleWrite ( "Online Mode - User not allowed" & @CRLF )

Query_Drives_and_Disconnect()

Else

consolewrite ( "Online Mode - User Allowed" & @CRLF )

; the option here is exit the script if the user is allowed.

EndIf

Else

consolewrite ( "Offline Mode" & @CRLF )

Query_Drives_and_Disconnect()

EndIf

EndIf

Next

Sleep (10000)

WEnd

; ---------------------------------

;

; FUNCTIONS

;

; ---------------------------------

Func ReportError($szMsg)

ConsoleWrite(StringFormat($szErrorFormat, _API_GetLastErrorMessage (), $szMsg) & @CRLF)

Exit

EndFunc ;==>ReportError

Func OpenVolume($cDriveLetter)

;HANDLE hVolume

;UINT uDriveType

;TCHAR szVolumeName[8]

;TCHAR szRootName[5]

;DWORD dwAccessFlags

$szRootName = StringFormat($szRootFormat, $cDriveLetter)

$uDriveType = DriveGetType($szRootName);

ConsoleWrite($szRootName & @tab & $uDriveType & @crlf)

Switch $uDriveType

Case "Removable"

$dwAccessFlags = 6

Case "CDROM"

$dwAccessFlags = 2

Case Else

ConsoleWrite("Cannot eject. Drive type is incorrect." & @CRLF)

Return $INVALID_HANDLE_VALUE

EndSwitch

$szVolumeName = StringFormat($szVolumeFormat, $cDriveLetter)

;$szVolumeName = $szVolumeFormat & $cDriveLetter

ConsoleWrite($szVolumeName & @crlf )

$hVolume = _API_CreateFile ($szVolumeName, 2,$dwAccessFlags, 6)

#cs

hVolume = CreateFile( szVolumeName,

dwAccessFlags,

FILE_SHARE_READ | FILE_SHARE_WRITE,

NULL,

OPEN_EXISTING,

0,

NULL );

#ce

If ($hVolume == $INVALID_HANDLE_VALUE) Then ReportError("CreateFile");

Return $hVolume;

EndFunc ;==>OpenVolume

Func CloseVolume($hVolume)

Return _API_CloseHandle ($hVolume);

EndFunc ;==>CloseVolume

Func LockVolume($hVolume)

Local $dwBytesReturned

Local $dwSleepAmount

Local $nTryCount

local $iRead

$dwSleepAmount = $LOCK_TIMEOUT / $LOCK_RETRIES;

; Do this in a loop until a timeout period has expired

For $nTryCount = 0 To $nTryCount < $LOCK_RETRIES

If _Device_Control($hVolume, $FSCTL_LOCK_VOLUME, $iRead) Then

Return True

Else

Sleep($dwSleepAmount);

EndIf

Next

Return False;

EndFunc ;==>LockVolume

Func DismountVolume($hVolume)

ConsoleWrite("Dismount " & $hVolume & @crlf)

Local $dwBytesReturned, $iRead

local $aResult = _Device_Control($hVolume, $FSCTL_DISMOUNT_VOLUME, $iRead)

;msgbox(0,"",$aResult)

Return $aResult

;Return $dwBytesReturned

EndFunc ;==>DismountVolume

Func PreventRemovalOfVolume($hVolume, $fPreventRemoval)

Local $dwBytesReturned

Local $aResult

Local $lpInbuffer,$nInBufferSize,$lpOutBuffer,$nOutBufferSize,$lpOverlapped

$PMRBUFFER = DllStructCreate("bool PreventMediaRemoval")

DllStructSetData($PMRBUFFER,"PreventMediaRemoval",$fPreventRemoval)

$lpBytesReturned = DllStructCreate("int Read")

$pRead = DllStructGetPtr($lpBytesReturned, "Read")

$aResult = Dllcall("kernel32.dll","int","DeviceIoControl","hwnd",$hVolume,"uint",$IOCTL_STORAGE_MEDIA_REMOVAL,"ptr",DllStructGetPtr($PMRBUFFER),"uint",DllStructGetSize($PMRBUFFER), _

"ptr",$lpOutBuffer,"uint",$nOutBufferSize,"ptr",$pRead,"ptr",$lpOverlapped)

if $aResult = 0 then msgbox(0,"",_API_GetLastErrorMessage())

Return $aResult <> 0

;& PMRBuffer, sizeof (PREVENT_MEDIA_REMOVAL),

;NULL, 0,

; & dwBytesReturned,

;NULL);

EndFunc ;==>PreventRemovalOfVolume

Func AutoEjectVolume($hVolume)

Local $aResult, $iRead;

$aResult = _Device_Control($hVolume, $IOCTL_STORAGE_EJECT_MEDIA, $iRead)

Return $aResult

EndFunc ;==>AutoEjectVolume

Func EjectVolume($cDriveLetter)

Local $hVolume;

Local $fRemoveSafely = False;

Local $fAutoEject = False;

; Open the volume.

$hVolume = OpenVolume($cDriveLetter);

If $hVolume == $INVALID_HANDLE_VALUE Then Return False

; Lock and dismount the volume.

If LockVolume($hVolume) And DismountVolume($hVolume) Then

$fRemoveSafely = True;

ConsoleWrite("Volume Locked and Dismounted, trying to eject " & @crlf)

; Set prevent removal to false and eject the volume.

If PreventRemovalOfVolume($hVolume, False) And AutoEjectVolume($hVolume) Then

$fAutoEject = True;

EndIf

Else

ConsoleWrite("Volume can't be locked or dismounted, please close possible opened files" & @crlf)

EndIf

; Close the volume so other processes can use the drive.

If CloseVolume($hVolume) = False Then

Return False;

EndIf

If $fAutoEject Then

ConsoleWrite(StringFormat("Media in Drive %s has been ejected safely.\n", $cDriveLetter))

Else

If $fRemoveSafely Then

ConsoleWrite(StringFormat("Media in Drive %s can be safely removed.\n", $cDriveLetter))

EndIf

EndIf

Return True;

EndFunc ;==>EjectVolume

Func _Device_Control($hDevice, $dwIoControlCode, ByRef $iRead)

Local $aResult

Local $lpInbuffer,$nInBufferSize,$lpOutBuffer,$nOutBufferSize,$lpOverlapped

$tRead = DllStructCreate("int Data")

$aResult = Dllcall("kernel32.dll","int","DeviceIoControl","hwnd",$hDevice,"uint",$dwIoControlCode,"ptr",$lpInBuffer,"uint",0, _

"ptr",$lpOutBuffer,"uint",0,"ptr",DllStructGetPtr($tRead),"ptr",$lpOverlapped)

$iRead = DllStructGetData($tRead, "Data")

ConsoleWrite("Device Control " & $iRead & @CRLF)

Return $aResult<>0

EndFunc ;==>_Device_Control

Func Query_Drives_and_Disconnect()

ConsoleWrite ( "Detected Device = " & $ItemFound.DeviceID & " - " & $ItemFound.Description & @CRLF )

$Event = $objWMIService.ExecQuery("Select * From Win32_LogicalDisk Where (DriveType = 2 and MediaType != 5 and (FileSystem = 'FAT' or FileSystem = 'FAT32'))" )

For $objItem in $Event

$OpenVolume = $objItem.DeviceID

ConsoleWrite ( $objItem.MediaType & @CRLF )

EjectVolume($OpenVolume)

MsgBox (16, "USB Drive Detected", "Drive " & $OpenVolume & " has been added to your PC." & @CRLF & @CRLF & "You are not authorised to use such portable media." & @CRLF & @CRLF & "This device has been automatically disconnected, please physically remove the device." & @CRLF & @CRLF & "Please contact the ICT dept. for further assistance.")

Next

$OpenVolume = ""

EndFunc

Func Check_AD_Link($Offline)

$objConnection = ObjCreate("ADODB.Connection") ; Create COM object to AD

$objConnection.Provider = "ADsDSOObject"

$objConnection.Open ("Active Directory Provider") ; Open connection to AD

$objRootDSE = ObjGet("LDAP://RootDSE")

$strDNSDomain = $objRootDSE.Get ("defaultNamingContext") ;Retrieve the current AD domain name (DN)

If @error then

$Offline = True

Else

$Offline = False

EndIf

ConsoleWrite ( "Offline = " & $Offline & @CRLF )

return $Offline

EndFunc

func ADErrors()

ConsoleWrite ( "Errors - " & $ADobjErrors.windescription & @CRLF )

SetError(1)

EndFunc

Func Memberof($AllowUser)

Dim $usergroups[1], $i = 1

Local $groups

$strQuery = "<LDAP://" & $strDNSDomain & ">;( samAccountName=" & @UserName & ");ADsPath;subtree"

$objRecordSet = $objConnection.Execute ($strQuery) ; Retrieve the FQDN for the logged on user

If $objRecordSet.RecordCount = 1 Then

$ldap_entry = $objRecordSet.fields (0).value

$oUsr = ObjGet($ldap_entry) ; Retrieve the COM Object for the logged on user

$groups = $oUsr.groups ; Get the list of group objects from the user

For $groupname In $groups

ReDim $usergroups[uBound($usergroups) + 1]

$usergroups[0] += 1 ; Increment the count of groups

$usergroups[$i] = StringTrimLeft($groupname.name, 3)

If $usergroups[$i] = $USB_Allow_Group Then

$AllowUser = True

ConsoleWrite ( "Allow = " & $AllowUser & @CRLF )

Return $AllowUser

EndIf

$i += 1

Next

EndIf

$AllowUser = False

ConsoleWrite ( "Allow = " & $AllowUser & @CRLF )

Return $AllowUser

EndFunc ;==>memberof


"My God, you're looking hideously ugly today, Ugly Bob."

Share this post


Link to post
Share on other sites

Can the normal user run it, or are you running it as admin or power user? As a normal user on my environment it doesn't work, I believe normal user can't access all the WMI functionality.

Today I did some more tests, and I found something different, maybe an hotfix changed the way usbstor driver works, anyone found the same? The previous routine I had to move the drivers will run into error when mounting the usb drive. Now the usbstor driver seems to be enabled or not just by the state: 3 for enabled or 4 for disabled (before I also had to remove the inf and png files, or remove their permissions)

An additional note UgglyBob: are you aware that if you run the script as another user, you are testing the user group of that user, not of the logged in user?

Oh and thanks for sharing your nice script! I will try to finish and improve mine. :)

Edited by BullGates

[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

Can the normal user run it, or are you running it as admin or power user? As a normal user on my environment it doesn't work, I believe normal user can't access all the WMI functionality.

I believe they can, well at least in my environment. Normal users are only a member of the local Users group and do not have any other elevated privileges to PCs.

An additional note UgglyBob: are you aware that if you run the script as another user, you are testing the user group of that user, not of the logged in user?

I am indeed. The purpose of the script is to run within the logged on user's session. This may change if the program is going to run as a service or something similar. However, I've updated the script slightly to include the disabling of the USBSTOR service (via RUNAS due to REGKEY permissions). This vastly improves the program as it doesn't have to continually run and monitor (basically it checks if any USB devices are currently connected, disconnects any if the user is not permitted then permanently disables the USBSTOR service). The idea is to use the script as part of Group Policy (as a logon script). My main concern is the use of USB devices whilst attached to the network. The plan is to set the USBSTOR service as disabled by default. Unless the script can prove that the logged on user is allowed it won't enable it, thereby preventing users from trying to circumvent the security restrictions (but I'm sure someone will find a way :) )...

There are a few things I need to iron out, but so far it works.

As a side issue, in your new script are the error events still caught by the ADerrors function? You seem to be missing the line:

$ADobjErrors = ObjEvent("AutoIt.Error", "ADErrors")

...or have I not got the correct understanding of how the objevent process works? (which wouldn't surprise me... ;) )

Edited by UglyBob

"My God, you're looking hideously ugly today, Ugly Bob."

Share this post


Link to post
Share on other sites

UglyBob: on your code you were not closing AD connections, if you have a large number of clients you can cause a large number of permanent connections to the Domain controller. I've dumped the COM routines and now I have a stable script with all the functionalities I want.


[topic="51913"]Restrict USB Storage usage to group membership[/topic] * [topic="48699"]Using nircmd library[/topic] * Some admin notes

Share this post


Link to post
Share on other sites

Slightly off topic but not really. How do you supress the insane urge Windows has to pop up a window asking you what action you want to take when you insert a USB device, ie a memory card or a memory stick, into a USB port ?

Share this post


Link to post
Share on other sites

the autostart screen is configurable by setting a registry key to false. if i remember well.

edit :

here is a regfile that do the job. But it disables autorun for CDs too.

http://www.flashenabled.com/noauto.reg

Edited by arcker

-- Arck System _ Soon -- Ideas make everything

"La critique est facile, l'art est difficile"

Projects :

[list] [*]Au3Service : Run your exe as service V3 / Updated 29/07/2013 Get it Here [/list]

Share this post


Link to post
Share on other sites

USB Monitor using WMI Event notification

Some one in the Support Section asked if it was possible to have a notification if a USB drive was Connected / Disconnected.

Well here is an example using the WMI Event notification :

$strComputer = "."
 $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")

 $colEvents = $objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceOperationEvent Within 5 Where " _
        & "TargetInstance isa 'Win32_LogicalDisk'")

While 1
     $objEvent = $colEvents.NextEvent
    If $objEvent.TargetInstance.DriveType = 2 Then 
        Select 
            Case $objEvent.Path_.Class()="__InstanceCreationEvent"
                Consolewrite("Drive " & $objEvent.TargetInstance.DeviceId & "has been added." & @CR)
            Case $objEvent.Path_.Class()="__InstanceDeletionEvent"
                Consolewrite("Drive " & $objEvent.TargetInstance.DeviceId & "has been removed."& @CR)
        EndSelect
    EndIf
WEnd

Enjoy !!

ptrex

@ptrex, your script does detect my USB drive, but how about external harddisk? It's part of USB drive family too rite? :P

which part of the script that i should add to detect my external harddisk?

TQ for your superb script :D


AUTOIT[sup] I'm lovin' it![/sup]

Share this post


Link to post
Share on other sites

@slayerz

You could add a test on the device the label.

This will return all USB related device and descriptions.

$strComputer = "."

$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")
$colDevices = $objWMIService.ExecQuery ("Select * From Win32_USBControllerDevice")

For $objDevice in $colDevices
    $strDeviceName = $objDevice.Dependent
    $strQuotes = Chr(34)
    $strDeviceName = StringReplace($strDeviceName, $strQuotes, "")
    $arrDeviceNames = StringSplit($strDeviceName, "=")
    $strDeviceName = $arrDeviceNames[2]
    $colUSBDevices = $objWMIService.ExecQuery ("Select * From Win32_PnPEntity Where DeviceID = '" & $strDeviceName & "'")
    For $objUSBDevice in $colUSBDevices
        MsgBox(0,"USB Description",$objUSBDevice.Description)
    Next
    MsgBox(0,"USB Devices",$strDeviceName)
Next

regards

ptrex


Share this post


Link to post
Share on other sites

Interestingly, a compact flash memory card, which Windows identifies as a removable drive and is connected via the usb port, is not detected by your script. Any ideas why ?

@ptrex, your script does detect my USB drive, but how about external harddisk? It's part of USB drive family too rite? :P

which part of the script that i should add to detect my external harddisk?

TQ for your superb script :D

Share this post


Link to post
Share on other sites

please can you tel me, how i can get the removal drive latter from this code like H: M: L:. i want to know which drive is latter is created by the removal detection...thank you...please

$strComputer = "."
 $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\cimv2")

 $colEvents = $objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceOperationEvent Within 5 Where " _
        & "TargetInstance isa 'Win32_LogicalDisk'")

While 1
     $objEvent = $colEvents.NextEvent
    If $objEvent.TargetInstance.DriveType = 2 Then 
        Select 
            Case $objEvent.Path_.Class()="__InstanceCreationEvent"
                Consolewrite("Drive " & $objEvent.TargetInstance.DeviceId & "has been added." & @CR)
            Case $objEvent.Path_.Class()="__InstanceDeletionEvent"
                Consolewrite("Drive " & $objEvent.TargetInstance.DeviceId & "has been removed."& @CR)
        EndSelect
    EndIf
WEnd
Edited by rafu

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...