I have a virtual hard disk .vhd file that I would like to backup on a daily basis by clicking on a shortc开发者_JAVA百科ut on my Windows Vista laptop. I wrote a half-hazard batch script file (BACKUP.BAT) which accomplishes the job, where it open the cmd window and copies the file to the flash drive, but I would like to mimic (macro) the way the copying is displayed when you manually drag and drop the file into the flash drive in my computer. Another problem is that depending on what computer this is done, the USB flash drive could have drive E: assigned to it (WinXP) and on other computers (Vista/7) it could be drive F:. (There doesnt seem to be a way to statically assign a fixed drive letter to the USB flash drive when it is inserted into the USB port.)
I would set the volume name of the disc, and examine all connected drives and find the drive with that volume name. Here's how I do it in PowerShell:
param([parameter(mandatory=$true)]$VolumeName,
[parameter(mandatory=$true)]$SrcDir)
# find connected backup drive:
$backupDrive = $null
get-wmiobject win32_logicaldisk | % {
if ($_.VolumeName -eq $VolumeName) {
$backupDrive = $_.DeviceID
}
}
if ($backupDrive -eq $null) {
throw "$VolumeName drive not found!"
}
# mirror
$backupPath = $backupDrive + "\"
& robocopy.exe $SrcDir $backupPath /MIR /Z
This code gets the last ready to use removable drive (e.g. an USB drive just plugged-in):
$drives = [System.IO.DriveInfo]::GetDrives()
$r = $drives | Where-Object { $_.DriveType -eq 'Removable' -and $_.IsReady }
if ($r) {
return @($r)[-1]
}
throw "No removable drives found."
This way does not require the fixed volume name to be pre-set. We can use different USB drives without knowing/setting their names.
UPDATE To complete drag-and-drop part of the task you can do this.
Create the PowerShell script (use Notepad, for example) C:\TEMP_110628_041140\Copy-ToRemovableDrive.ps1 (the path is up to you):
param($Source)
$drives = [System.IO.DriveInfo]::GetDrives()
$r = $drives | Where-Object { $_.DriveType -eq 'Removable' -and $_.IsReady }
if (!$r) {
throw "No removable drives found."
}
$drive = @($r)[-1]
Copy-Item -LiteralPath $Source -Destination $drive.Name -Force -Recurse
Create the file Copy-ToRemovableDrive.bat (for example on your desktop), it uses the PowerShell script:
powershell -file C:\TEMP\_110628_041140\Copy-ToRemovableDrive.ps1 %1
Now you can plug your USB drive and drag a file to the Copy-ToRemovableDrive.bat
icon at your desktop. This should copy the dragged file to the just plugged USB drive.
精彩评论