Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Detect USB Flash Drive & Run Batch File

Status
Not open for further replies.

Nu2Java

Technical User
Jun 5, 2012
166
US
Hi, I am working on a small script here to detect a flash drive and then run a backup file (batch file). It works pretty well the first time around when I plug in the correct drive that has the label I am requiring, but when I plug in another drive, remove it and plug the correct one back in, it fails on me and shows "Object Required" which points to my batch file, like it cannot find it the 2nd time.

Can anyone tell me where I am going wrong? Thanks for any help...

Code:
Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

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

Do While True
    Set objEvent = colEvents.NextEvent
    If objEvent.TargetInstance.DriveType = 2 Then 
        Select Case objEvent.Path_.Class
            Case "__InstanceCreationEvent"
                Wscript.Echo "Flash Drive " & objEvent.TargetInstance.DeviceId & _
                    " has been added to the system."

'get label name
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
    ("Select * From Win32_LogicalDisk Where DeviceID = 'R:'")


For Each objItem in colItems
    'Wscript.Echo objItem.VolumeName
If objItem.VolumeName = "KINGSTON64" Then
'MsgBox"Correct Flash Drive Inserted"
objShell.Run("c:\Users\mike\desktop\backups.bat")
Set objShell = Nothing
Else
MsgBox"Incorrect Backup Drive, No backup will be performed!", vbExclamation
End If 
Next


            Case "__InstanceDeletionEvent"
                Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _
                    " has been removed from the system."
        End Select
    End If
Loop
 
Get rid of this line:
Set objShell = Nothing

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Ahhh huh... that makes perfect sense. Thanks, PHV & Guitarzan for your help!
 
Ok, I am back at this again. It seems to work good except now I am writing to a text file when the flash drive has been detected. It works fine when I run it the first time, but when I remove the flash drive and then re-insert it, I get an error for appending to the text file. Is my "write text" code in the wrong spot? I'm not sure what is going on... any help would be great. Thanks



Code:
Dim objShell
Dim objFile, strDir, strExt, strUpdate

Set objShell = WScript.CreateObject( "WScript.Shell" )

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

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

Do While True
    Set objEvent = colEvents.NextEvent
    If objEvent.TargetInstance.DriveType = 2 Then 
        Select Case objEvent.Path_.Class
            Case "__InstanceCreationEvent"
                Wscript.Echo "Flash Drive " & objEvent.TargetInstance.DeviceId & _
                    " has been added."
					
strDir = ("C:\Temp2\")

Const ForAppending = 8
Const ForReading = 1

set objFSO = CreateObject("Scripting.FileSystemObject")
strExt = "Flash_Drive_Log"
strUpdate = "Flash Drive Detected on System: " & Now

set objFile = objFSO.OpenTextFile(strDir & strExt & ".txt", ForAppending, True)
objFile.WriteLine strUpdate
objFile.Close

'get label name
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
    ("Select * From Win32_LogicalDisk Where DeviceID = 'E:'")



For Each objItem in colItems
    'Wscript.Echo objItem.VolumeName
If objItem.VolumeName = "KINGSTON64" Then
'MsgBox"Correct Flash Drive Inserted"
objShell.Run("""c:\Users\mike\desktop\backups.bat""")
'Set objShell = Nothing
Else
MsgBox"Incorrect Backup Drive, No backup will be performed!", vbExclamation
End If 
Next

            Case "__InstanceDeletionEvent"
                Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _
                    " has been removed."
        End Select
    End If
Loop
 
Probably related to defining the constants inside the loop.
Move the lines below to the top of the script, or at least before the "Do While" loop:
Const ForAppending = 8
Const ForReading = 1
 
Thanks, guitarzan... that did it.

Below is the batch file I am using to perform my backup. Is there a way to do this in the vbscript file? What I like about the batch file is, it shows the files being backed up in the command window and only copies the files that were changed. So I like the visual confirmation of the files that were copied over.

What I would like to know is, can the same thing be done in vbscript? Would it be a message to show the files that changed and were copied? Also, I would like to know if the backup failed and/or how many files were backed up.

Code:
@echo off
:: variables
set drive=E:\Backup
set backupcmd=xcopy /s /c /d /e /h /i /r /y

echo Backup in progress...
%backupcmd% "%USERPROFILE%\Desktop\TEMP MISC" "%drive%\TEMP MISC\"

echo Your Backup is Complete!
@pause
 
Sure, but it would be much more involved than simply executing a single "XCOPY" command.

You could use the FileSystem object to recursively go through every file (including subfolders), as demonstrated in this FAQ:
faq329-5515

You could compare the DateLastModified property of the File object (see below) to the same location on the target...

... and if it's newer, execute the FileCopy method to copy the file to the target. And check the Err.Number after each copy to make sure it's 0, otherwise show an error message. Oh, and make sure you create folders on the target.

Or you can use XCOPY. ROBOCOPY has some nice features as well
 
Thanks a lot for your time and help. I will check out the links you provided and see if I can implement something.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top