locked
Make batch/vbscript do something if removable disks exist, how to do this? RRS feed

  • Question

  • I already know how to check if theres removable disks connected with cmd with the following command: wmic logicaldisk where drivetype=2 get deviceid, volumename, description

    but now I would like to make a batch that checks if theres any removable disks connected it executes another command or runs another batch.

    So it would be something like

    if drivetype=2 exists then "command"

    How would this be possible? Or is it even?
    Im also interested in VBScript methods if batch is not possible.

    I really hope there's a way to do this. Thanks in advance to anyone who can help me.


    • Edited by Samu Kuosmanen Sunday, December 15, 2013 4:00 PM fixed typos
    Sunday, December 15, 2013 3:59 PM

Answers

  • I'd recommend that you start working with PowerShell as soon as you can, but here's how you could do it in VBScript or batch:

    # Batch:
    
    wmic LogicalDisk where DriveType=2 get DeviceID | findstr /I DeviceID > nul 2>&1
    
    if %errorlevel% == 0 (
        echo A removable drive exists, do something here.
    )
    
    
    # VBScript:
    
    Set objWmiSvc = GetObject("winmgmts://./root/cimv2")
    Set colDrives = objWmiSvc.ExecQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 2")
    
    If colDrives.Count > 0 Then
        WScript.Echo "A removable drive exists, do something here."
    End If


    • Edited by David Wyatt Sunday, December 15, 2013 4:08 PM
    • Marked as answer by Samu Kuosmanen Sunday, December 15, 2013 4:35 PM
    Sunday, December 15, 2013 4:07 PM

All replies

  • I'd recommend that you start working with PowerShell as soon as you can, but here's how you could do it in VBScript or batch:

    # Batch:
    
    wmic LogicalDisk where DriveType=2 get DeviceID | findstr /I DeviceID > nul 2>&1
    
    if %errorlevel% == 0 (
        echo A removable drive exists, do something here.
    )
    
    
    # VBScript:
    
    Set objWmiSvc = GetObject("winmgmts://./root/cimv2")
    Set colDrives = objWmiSvc.ExecQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 2")
    
    If colDrives.Count > 0 Then
        WScript.Echo "A removable drive exists, do something here."
    End If


    • Edited by David Wyatt Sunday, December 15, 2013 4:08 PM
    • Marked as answer by Samu Kuosmanen Sunday, December 15, 2013 4:35 PM
    Sunday, December 15, 2013 4:07 PM
  • Thank you so much for quick response! This is awesome, thank you again!

    Why is it so important to use PowerShell instead VBScript?

    Sunday, December 15, 2013 4:36 PM
  • PowerShell is the command-line interface that Microsoft is actively supporting and updating.  Batch and Windows Script Host are older technologies that won't support anything new as OS versions are released.
    Sunday, December 15, 2013 5:31 PM