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

前端 未结 2 1233
旧巷少年郎
旧巷少年郎 2021-01-07 01:52

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 fi

2条回答
  •  孤街浪徒
    2021-01-07 02:33

    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.

提交回复
热议问题