Skip to content

Instantly share code, notes, and snippets.

@JMatthewman
Created November 8, 2012 23:26
Show Gist options
  • Save JMatthewman/4042583 to your computer and use it in GitHub Desktop.
Save JMatthewman/4042583 to your computer and use it in GitHub Desktop.
Powershell script to listen for drive connection, check if it matches a predefined list and run the required sync.
# Memory Stick Backup Syncronisation script
# By Joel Matthewman 08/11/2012
#
# Customizations:
# Ln 13 path to SyncToyCMD.exe (you may need to change to x86 or other obscure location)
# Ln 23 Location of dropbox.exe
# Ln 29 Drive definitions with drive letter and name, and names of any SyncPairs to syncronise
#
#
function syncToy ($folderPairs) {
msg "Starting SyncToy"
foreach ($folderPair in $folderPairs) {
msg "Syncing $folderPair"
start-process "C:\Program Files\SyncToy 2.1\SyncToyCmd.exe" "-R $($folderPair)" -wait
}
msg "SyncToy complete."
}
function dropbox {
msg "Restarting DropBox"
stop-process -name DropBox
msg "DropBox stopped."
msg "Starting new instance of DropBox"
start-process "C:\Users\Joel\AppData\Roaming\Dropbox\bin\Dropbox.exe"
msg "DropBox started."
}
function recognise {
switch -wildcard ($driveDetails) {
"R: SOURCY FOUR" {msg "Drive recognised, sync not configured"}
"Z: MOLEMAN" {msg "Drive recognised."; syncToy "College","Minecraft","PuTTy Config"; dropbox;}
"X: MoleMan's Snaps & Tunes" {msg "Drive recognised."; syncToy "Snaps","Music -- 2.5'' - Shared Music"; dropbox;}
default {msg $driveDetails " has no defined Sync."}
}
}
function msg ($msg) {
write-host (get-date) "`t`t"$msg
}
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
msg "Beginning script..."
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"}
}
msg "Event detected = $eventTypeName"
if ($eventType -eq 2)
{
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
$driveDetails = "$driveLetter $driveLabel"
msg "Drive = $driveDetails"
recognise
}
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