How can I create a PowerShell script to copy a file to a USB flash drive?

拈花ヽ惹草 提交于 2019-12-03 21:53:15

问题


I have a virtual hard disk .vhd file that I would like to backup on a daily basis by clicking on a shortcut 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.)


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6500277/how-can-i-create-a-powershell-script-to-copy-a-file-to-a-usb-flash-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!