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

前端 未结 2 1234
旧巷少年郎
旧巷少年郎 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:31

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题