powershellshellscriptingrobocopy

Move a List of Folders from csv File without losing the permissions


I am trying to move a list of user folders to a new file server so I need to keep the permissions intact. For that I am using robocopy. The problem is, it will only move the files and subfolders inside the source folder but not the source folder itself. this is the script I am using:

   function Move-Folders {
   param(
       [Parameter(Mandatory=$true)]
       [string]$Csv
   )

   $folders = Import-Csv -Path $Csv
   $Target = "\\Server\share\"

   foreach ($folder in $folders) {
       $folderPath = $folder.Path
       Write-Host "moving folder $folderPath"

       try {
           robocopy $folderPath $Target /E /COPYALL /MOVE /NP
       } catch {
           $errorMessage = $_.Exception.Message
           Write-Host -ForegroundColor Yellow "Error Moving folder $folderPath : $errorMessage"
       }
   }
}

also it will not display the error message I wrote in the catch, if an Error occurred. Can someone please help. how do I get the command to move the source folders that is writen in the CSV file this is my first time using Robocopy so if you guys have any modifications to the command feel free to add it. The csv Path Column is writen this way \\Server\folder


Solution

  • You could try to get the directoryname itself with:

    $dir = $folderPath -replace ".*\\"
    

    Then adding the directory Name to the robocopy command:

    robocopy "$folderPath\" "$Target\$dir" /E /COPYALL /MOVE /NP
    

    Complete Script would then look like this:

    function Move-Folders {
       param(
           [Parameter(Mandatory=$true)]
           [string]$Csv
       )
    
       $folders = Import-Csv -Path $Csv
       $Target = "\\Server\share"
    
       foreach ($folder in $folders) {
           $folderPath = $folder.Path
           Write-Host "moving folder $folderPath"
    
           $dir = $folderPath -replace ".*\\"
    
           try {
               robocopy "$folderPath\" "$Target\$dir" /E /COPYALL /MOVE /NP
           } catch {
               $errorMessage = $_.Exception.Message
               Write-Host -ForegroundColor Yellow "Error Moving folder $folderPath : $errorMessage"
           }
       }
    }
    

    Maybe it would be just better to edit the CSV File with more informations and getting the needed Folders directly from the CSV.