Skip to content

Commit 2a8e749

Browse files
committed
Published
1 parent 61b5da9 commit 2a8e749

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

registerusbevent.ps1

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#
2+
# registerusbevent.ps1
3+
#
4+
# Register a new Windows event when a USB stick is inserted in a USB port.
5+
# Kudos to Jose for the original version of the script ;-)
6+
#
7+
# Author: Xavier Mertens <[email protected]>
8+
# CopyRight: GPLv3 (http://gplv3.fsf.org)
9+
# Free free to use the code but please share the changes you've made
10+
#
11+
12+
$query = "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"
13+
14+
Register-WmiEvent -Query $query -SourceIdentifier RemovableDiskDetection -Action {
15+
16+
$class = $eventArgs.NewEvent.__CLASS
17+
$device = $eventArgs.NewEvent.TargetInstance.DeviceID
18+
19+
switch($class)
20+
{
21+
__InstanceCreationEvent {
22+
Write-Host "[DEBUG] Inserted, device id: $device "
23+
$path = $device + "\log\processing.log"
24+
Write-Host "[DEBUG] Checking the existence of the file $path"
25+
$ok = $false
26+
27+
# Test the presence of a CIRCLean logfile and check its age (must be < 2d)
28+
if(Test-Path -Path $path)
29+
{
30+
Write-Host "[DEBUG] Looking for the creation date of the file $path"
31+
$lastModification = (get-item $path).LastWriteTime
32+
$timeSpan = new-timespan -days 2
33+
if (((get-date) - $lastModification) -lt $timeSpan) {
34+
Write-Host "[DEBUG] The file $path has been created/modified in less than 2 days"
35+
$ok = $true
36+
}
37+
}
38+
else {
39+
Write-Host "[DEBUG] Tag file does not exist."
40+
}
41+
42+
# File not found or too old, eject and notify the user via a popup window
43+
if (!$ok)
44+
{
45+
$driveEject = New-Object -comObject Shell.Application
46+
$driveEject.Namespace(17).ParseName($device).InvokeVerb("Eject")
47+
Write-Host "[DEBUG] The USB stick is considered NOT SAFE. In order to use it please scan it first using CIRCLean."
48+
(new-object -ComObject wscript.shell).Popup("This USB stick is considered NOT safe. Please scan it with CIRCLean!",0,"USB Cleaner",0x0)
49+
}
50+
else{
51+
Write-Host "[DEBUG] The USB stick is considered SAFE."
52+
}
53+
}
54+
55+
__InstanceDeletionEvent {
56+
Write-Host "[DEBUG] Removed, device id: $device "
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)