user3605317
user3605317

Reputation: 143

Copy using the folder names from .csv

I have a .csv in this format (with two columns ID and DisplayName) under D:\temp ID DisplayName jdoe Doe, John msmith Smith, Mark lpratt Pratt, Liz ....... and so on

There is a folder (E:\data)on the server under which there are folders with userid with some data already. For ex: E:\data\jdoe, E:\data\msmith and so on. I want to write a script that will create a new folder E:\New_data\Smith, Mark and copy the data from E:\data\msmith.

I tried this code:

   $csv = Import-Csv D:\Temp\temp.csv
   ForEach ($obj in $csv.ID) {
   Foreach ($obj1 in $csv.DisplayName) {
   copy-item D:\Data\$obj D:\New_data\$obj1 -Recurse -Force
   }
   }

But this one is copying all the folders in the old location to every folder being copied to the new location. I kindly request you to let me know what am I missing? Thanks

Upvotes: 1

Views: 266

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19654

When you use Import-Csv, each row is loaded as a pscustomobject with fields that match the column headers. In your case, you want to iterate through each of these (your double foreach doesn't actually accomplish anything):

$csv = Import-Csv -Path D:\Temp\temp.csv
foreach ($row in $csv)
{
    $source = $row.ID
    $dest = $row.DisplayName
    Copy-Item -Path "D:\Data\$source" -Destination "D:\New_data\$dest" -Recurse -Force
}

Upvotes: 2

Related Questions