cormanaz has asked for the wisdom of the Perl Monks concerning the following question:

Good day bros. I want to write a script that will automatically copy files from a flash drive to a backup directory on my hard drive. I have given the drive a particular name, but since it might be plugged into the USB along with other devices I can't be sure it will always have the same drive letter. So the question is, how do I read the entries in "my computer" to look for the drive with a given name?

opendir/readdir presumes (as far as I can tell) that you can specify the drive letter. I looked at Win32::FileOp for a solution. It would let me browse for it with a dialog box, but I want to find the drive letter without browsing by reading the items in "my computer" a picking the one with the correct name.

Your advice appreciated.

Steve

Replies are listed 'Best First'.
Re: Locating a flash drive on windows
by cormanaz (Deacon) on Oct 11, 2007 at 22:52 UTC
    You would think this would be a simple thing to do, but you would be wrong. I found an answer myself at Microsoft TechNet. Here's an adaptation of the code to do the job I requested:
    use strict; use Win32::OLE('in'); use constant wbemFlagReturnImmediately => 0x10; use constant wbemFlagForwardOnly => 0x20; my $flashdriveletter; my $flashdrivename = 'foo'; my $computer = "."; my $objWMIService = Win32::OLE->GetObject("winmgmts:\\\\$computer\\roo +t\\CIMV2") or die "WMI connection failed.\n"; my $colItems = $objWMIService->ExecQuery("SELECT * FROM Win32_LogicalD +isk","WQL",wbemFlagReturnImmediately | wbemFlagForwardOnly); foreach my $objItem (in $colItems) { if ( $objItem->{VolumeName} eq /$flashdrivename/ ) { $flashdriveletter = $objItem->{Caption}; } }

    The page lists about a zillion other attributes of the drive you can get from $objitem.

    Steve

Re: Locating a flash drive on windows
by Anonymous Monk on Oct 11, 2007 at 22:51 UTC

    Hi,

    I use the following to get drive info on Windows XP.

    use Win32API::File qw( :Func ); %driiv_name = (); @drives_volumes = (); @driivs = (); sub find_drives { eval{ @driivs= getLogicalDrives(); }; if( $@ ) { my $msg = $mw->MesgBox( -title => 'Fatal Error.', -text => "No Logical Drives found.", -icon => 'ERROR', -buttons => ['OK'] )->Show; } my $lup = 0; my $endlup = scalar( @driivs ); while( $lup < $endlup ) { $sRootPath = $driivs[$lup]; GetVolumeInformation( $sRootPath, $osVolName, $lVolName, $ouSerialNum, $ouMaxNameLen, $ouFsFlags, $osFsType, $l +FsType ); $drives_volumes[$lup] = sprintf "%-5s%15s", $sRootPath, $osVol +Name ; $driiv_name{$drives_volumes[$lup]} = $sRootPath; $lup++; } $FS_Tname = $drives_volumes[0]; $FD_Tname = $drives_volumes[0]; }


    This is a stripped down version.
    Hopefully I haven;t taken out anything vital.

    J.C.