powershell - 使用具有长路径的 Robocopy 复制单个文件
问题描述
下面的脚本是从“发送到”文件夹中的快捷方式运行的。通过右键单击文件并从“发送到”菜单中选择相关菜单项,该文件被复制到 Documents 中的一个特殊文件夹,然后在其默认应用程序中打开。它适用于最多 260 个字符的路径,但如果路径超过该限制,则会失败。
我尝试使用 Robocopy(请参阅脚本),但显然长路径问题也影响了拆分路径,因此我无法获取源文件夹或文件名。
有解决办法吗?它不必使用 Robocopy。复制的文件覆盖旧文件是可以的。
#Get the source file path and name
param([string]$SourceFile)
#Shared folder workaround Part 1
#---------------------------------------------------------------------------------------------------
New-PSDrive -Name source -PSProvider FileSystem -Root \\machine1\abc\123 | Out-Null
New-PSDrive -Name target -PSProvider FileSystem -Root \\machine2\c$\Logs | Out-Null
#---------------------------------------------------------------------------------------------------
#Create the the destination folder string Part 1 - get the profile's Documents path
[string]$DestinationFolder = [Environment]::GetFolderPath("MyDocuments")
#Create the the destination folder string Part 2 - add the folder's name to which the file will be copied
$DestinationFolder = "$DestinationFolder\folder to receive the files\"
#Create the destination folder if it does not exist
New-Item -ItemType Directory -Force -Path $DestinationFolder
#Copy the source file to the destination folder, quotes added to encapsulate spaces (this fails with long paths)
Copy-Item -Path "$SourceFile" -Destination $DestinationFolder
#Tried using Robocopy but apparently can't get the path or file name due to long file path issue
#Robocopy Split-Path -Path "$SourceFile" $DestinationFolder Split-Path "$SourceFile" -Leaf
#Shared folder workaround Part 2
#---------------------------------------------------------------------------------------------------
Remove-PSDrive source
Remove-PSDrive target
#---------------------------------------------------------------------------------------------------
#Get the copied file name, quotes added to encapsulate spaces
[string]$NewFile = Split-Path "$SourceFile" -Leaf
#Add the destination folder to the string
$NewFile = $DestinationFolder + $NewFile
#Open the copied file
Invoke-Item -Path $NewFile
编辑
据我所知,第一行代码就是问题所在。
param([string]$SourceFile)
如何编辑它以使用长文件名?
Wasif 在下面的评论中建议我\\?\
之前使用$SourceFile
. 我已经尝试过"\\?\$SourceFile"
,但它不起作用。我还尝试编辑 SendTo 文件夹中的快捷方式属性。那也没有用。
解决方案
您可以前缀\\?\
使 windows API 不遵循 260 字符限制:
$DestinationFolder = "\\?\$($DestinationFolder)\folder to receive the files\"
推荐阅读
- mysql - NodeJS - MySQL 查询
- node.js - 我应该在数据库中保留多少个网络推送订阅对象?
- python - 如果可能的话,你能让我的代码更干净吗?
- kubernetes - 在日志模式中提供多个容器名称以从中刮取数据
- php - PDF生成后如何禁用浏览器中显示的TCPDF版本
- unity3d - UNITY:一切看起来都是低分辨率的。甚至 SVG 矢量
- html - 减少文本网格行之间的间隙
- ios - 无法在 react native 0.65 上升级和构建 iOS
- c# - 如果我有多个这样的 if else 语句,您如何考虑重构它?
- sql - 如何在presto中将列转换为数组