Created
July 24, 2015 10:41
-
-
Save koenmetsu/33992807c57e0092e984 to your computer and use it in GitHub Desktop.
Ps file to automatically detect usb disk being inserted, calls bat to load vhd and tries to run a script on the newly loaded virtual disk.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -version 2.0 | |
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange | |
write-host (get-date -format s) " Beginning script..." | |
$DrivesCount = (gwmi -Query "Select * from Win32_LogicalDisk").Count | |
$Drives = (gwmi -Query "Select * from Win32_LogicalDisk") | |
do{ | |
$newEvent = Wait-Event -SourceIdentifier volumeChange | |
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType | |
$eventTypeName = switch($eventType) | |
{ | |
1 {"Configuration changed"} | |
2 {"Device arrival"} | |
3 {"Device removal"} | |
4 {"docking"} | |
} | |
write-host (get-date -format s) " Event detected = " $eventTypeName | |
if ($eventType -eq 2) | |
{ | |
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName | |
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName | |
write-host (get-date -format s) " Drive name = " $driveLetter | |
write-host (get-date -format s) " Drive label = " $driveLabel | |
# Execute process if drive matches specified condition(s) | |
if ($driveLabel -eq 'Tonberry') | |
{ | |
write-host (get-date -format s) " Starting Tonberry run in 3 seconds..." | |
start-sleep -seconds 3 | |
start-process "E:\runsomething.bat" -WindowStyle Hidden | |
start-sleep -seconds 10 | |
$tries = 12 # => 2 mins of tries | |
$success = 0 | |
do | |
{ | |
write-host (get-date -format s) " Trying to setup tools..." | |
if(Test-Path "Q:\somebat.bat") { | |
start-process "Q:\somebat.bat" -WindowStyle Hidden | |
$tries = 0 | |
$success = 1 | |
} | |
else { | |
write-host (get-date -format s) " Tools not found, will try again in 10 secs..." | |
$tries-- | |
start-sleep 10 | |
} | |
} while ($tries -ne 0 -and (Test-Path "E:\runsomething.bat")) | |
if($success -eq 1){ | |
write-host (get-date -format s) " Tools set up!" | |
$wshell = New-Object -ComObject Wscript.Shell | |
$wshell.Popup("Tools set up.",0,"Tools setup",0x1) | |
}else{ | |
write-host (get-date -format s) " Tools not found, I'm giving up." | |
$wshell = New-Object -ComObject Wscript.Shell | |
$wshell.Popup("Tools not found, I'm giving up.",0,"Could not initialize tools...",0x1) | |
} | |
} | |
} | |
Remove-Event -SourceIdentifier volumeChange | |
} while (1-eq1) #Loop until next event | |
Unregister-Event -SourceIdentifier volumeChange |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment