我正在Windows 7中使用Powershell 2.0。
我想使用cmd或powershell将USB记忆棒中的文件复制到主硬盘驱动器上的目录中。但是,我需要在没有输入USB当前驱动器号的任何PC上运行它。如果这没有意义,请让我改一下。我需要一个powershell或cmd命令/批处理脚本,无需任何输入即可将文件从USB闪存盘复制到硬盘驱动器。
理想的命令会将变量mydrive分配给驱动器号,并允许我在cmd中运行类似的内容
copy myvar:/path/fileToCopy.txt/ C:/path/of/target/directory/
如果能仅使用我的USB记忆棒名称('DD')进行这样的复制,我将不胜感激:
copy DD:/path/fileToCopy.txt/ C:/path/of/target/directory/
我在一个多小时的研究中做得很好,试图找到一种方法来实现这一目标,而不能做到。任何帮助是极大的赞赏。特别是如果清楚如何使用它。我对powershell和cmd命令非常陌生,并且不了解语法。因此,[在这里输入驱动器名称]这样的东西来告诉我如何使用它将是惊人的,并且很多论坛都在这里丢失。
您可以按照以下步骤进行操作:
$destination = 'C:\path\of\target\directory'
$sourceFile = 'path\fileToCopy.txt' # the path to the file without drive letter
# get (an array of) USB disk drives currently connected to the pc
$wmiQuery1 = 'ASSOCIATORS OF {{Win32_DiskDrive.DeviceID="{0}"}} WHERE AssocClass = Win32_DiskDriveToDiskPartition'
$wmiQuery2 = 'ASSOCIATORS OF {{Win32_DiskPartition.DeviceID="{0}"}} WHERE AssocClass = Win32_LogicalDiskToPartition'
$usb = Get-WmiObject Win32_Diskdrive | Where-Object { $_.InterfaceType -eq 'USB' } |
ForEach-Object {
Get-WmiObject -Query ($wmiQuery1 -f $_.DeviceID.Replace('\','\\')) #'# double-up the backslash(es)
} |
ForEach-Object {
Get-WmiObject -Query ($wmiQuery2 -f $_.DeviceID)
}
# loop through these disk(s) and test if the file to copy is on it
$usb | ForEach-Object {
# join the DeviceID (like 'H:') with the file path you need to copy
$file = Join-Path -Path $_.DeviceID -ChildPath $sourceFile
if (Test-Path -Path $file -PathType Leaf) {
Copy-Item -Path $file -Destination $destination
break # exit the loop because you're done
}
}
希望有所帮助
如果升级PowerShell的版本,则可以将Get-WmiObject
替换为Get-CimInstance
,以获得更好的性能。参见this和that
Windows 10 64位。 PowerShell 5和PowerShell 7.0.0-rc.1
在PowerShell 5中为我工作:
(gwmi win32_volume -f 'label=''ESD-USB''').Name
在PowerShell 7.0.0-rc.1中对我不起作用
(gwmi win32_volume -f 'label=''ESD-USB''').Name
(get-psdrive | Where-Object {$_.name -eq "ESD-USB"}).Root
在PowerShell 5中对我不起作用
(get-psdrive | Where-Object {$_.name -eq "ESD-USB"}).Root