【发布时间】:2021-04-02 01:54:03
【问题描述】:
下面的脚本是从“发送到”文件夹中的快捷方式运行的。通过右键单击一个文件并从“发送到”菜单中选择相关菜单项,该文件被复制到 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 在下面的 cmets 中建议我在 $SourceFile 之前使用 \\?\。我已经在"\\?\$SourceFile" 中尝试过,但它不起作用。我还尝试在 SendTo 文件夹中编辑快捷方式属性。那也没用。
【问题讨论】:
-
提示:更新您的问题时,可以无缝地合并其他材料(如果没有多少人看过,而您没有任何答案),或者在最后添加附录。问题得到的未来读者比过去的读者多得多,因此最好迎合未来的读者 - 他们会被按时间倒序编写的问题弄糊涂。
-
如果您想回滚,请联系 cmets 中的编辑 - 您可以使用他们的
@nameping 他们。关于如何编写/编辑问题的元评论不属于问题,就像关于如何编写维基百科文章的元评论不属于维基百科文章一样。 -
所有元问题can be asked on Meta Stack Overflow(您的元问题可能已经在那里提出过)。
-
“我应该在单独的帖子中再次询问吗?” - 有时这是个好主意。我认为,如果您的补充问题与原始问题非常紧密地绑定,则可以进行小的更新,然后通过在他们的问题下发表评论来 ping 回答者。额外的小问题是否值得提出新问题可能是主观的。
标签: powershell