Copy folders using csv in powershell

Akshay Solanki 1 Reputation point
2021-09-20T16:26:14.88+00:00

Hello,
I am fairly new to powershell with little to no experience in scripting. I have a task to copy folders from source to destination but it has some tricky part in it.
I have one source folder C:\source\ where all the folders and subfolders are resided.
133732-issue1.png

And I have a csv file where I have two separate columns to copy from source to destination.

C:\dest\company1\

C:\dest\company2\

IE two different companies have folders in same source folder so need to copy them and paste it in different destination folders.
133712-issue2.png

Here is the code I tried with some understanding from the internet.

$source       = Get-Childitem "C:\source"  
$destination1 = "C:\dest\company1\"  
$destination2 = "C:\dest\company2\"  
$csv          = import-csv "C:\Scripts\copytask.csv"  
  
foreach ($row in $csv) {  
    if($source -contains $row.company1){  
        robocopy "C:\source\$($row.company1)*" $destination1 /E   
    }  
    elseif($source -contains $row.company2){  
        robocopy "C:\source\$($row.company2)*" $destination2 /E   
    }  
}  

but I am not getting any output when I run the script and not copying as well.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,453 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 32,736 Reputation points
    2021-09-20T17:01:19.297+00:00

    If your images are correct, then $($row.company1) will contain '11', but the actual folder name is 'folder(11)'.

    You need to look at the folder names.

     if(($source).Name -contains $row.company1){
    

    With robocopy, you need to put the folder names in both the source and destination parameters. I don't think that you want to just use $destination1 as the second parameters

    Here is my reply to your first post.

    I didn't fully test this, but give it a try. I added "/l" to robocopy so that it didn't spam your file system if the names were wrong. This assumes that you want to copy c:\Source\Folder11 to c:\Dest\Company1\Folder11.

    $source =  "C:\source"
    $destination1 = "C:\dest\company1\"
    $destination2 = "C:\dest\company2\"
    $csv = import-csv "C:\Scripts\copytask.csv"
    $srcFolders = Get-ChildItem -Path $source
    
     foreach ($folder in $SrcFolders) {      
        foreach($row in $csv) {
            if($Folder.name -match $row.company1 ) {                # does 'folder(11)' contain '11'?    
                robocopy "C:\source\$($Folder.Name)" "$destination1$($folder.Name)" /E /L    
            }
         }    
     }