2021年4月1日星期四

Copy a single file using Robocopy with long path

The script below is run from a shortcut in the "Send To" folder. By right-clicking a file and selecting the relevant menu item from the "Send to" menu, the file is copied to a special folder in Documents, then opened in it's default application. It works fine with paths up to 260 characters, but fails if a path exceeds that limit.

I tried to use Robocopy (refer to script), but apparently the long path issue is also affecting Split-Path so I can't get the source folder or file name.

Is there a solution? It doesn't have to use Robocopy. Copied files overwriting older files is okay.

#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  
https://stackoverflow.com/questions/66913569/copy-a-single-file-using-robocopy-with-long-path April 02, 2021 at 09:54AM

没有评论:

发表评论