Author Posts

September 13, 2016 at 1:24 am

Hey guys! I am currently trying to pull a list of names from a CSV file and creating directories for each name.
The original directory I want to copy is the variable ($Folder). (There are other folders within it hence the -recurse)

The CSV has two columns firstname, lastname and various dummy names in the following rows.

I am getting the first row/name coming back perfect, but it seems I can't figure out how to do a loop of each row after that one.
I have been looking all over the net for a solution. Thanks for your time, any help would be appreciated.

  • This topic was modified 2 years ago by  JP.

September 13, 2016 at 2:12 am

Because your getname function returns after the first iteration through data imported it will only return the first row.
something like this may be more useful to you

$ImportCsv = Import-Csv -Path $Csv
foreach($row in $ImportCsv ) {
    $firstname = $row.firstname 
    $lastname =  $row.lastname
    $name = "$firstname$lastname"
    Copy-item $Folder\* -destination "C:\Users\jp\Desktop\folderscript\testfolder\$($name)" -Recurse

September 13, 2016 at 2:16 am

You are a deadset legend! Thank you so much Jonathan!

September 13, 2016 at 12:48 pm

You can simplify this a bit more. If you look at "Get-Help Copy-Item -Full", you'll see that you can pass the Path and Destination by ByPropertyName:

        Required?                    true
        Position?                    0
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Parameter set name           Path
        Aliases                      None
        Dynamic?                     false

If we utilize calculated expressions, you can name the property to Path and Destination respectively. Then you can pipe the data directly to Copy-Item:

$csv = Import-Csv -Path C:\Users\Rob\Desktop\Archive\test.csv | 
Select FirstName,
       @{Name="Destination";Expression={"C:\Users\Rob\Desktop\{0}{1}" -f $_.FirstName, $_.LastName}}
$csv | Copy-Item -WhatIf 

If the column doesn't match a parameter (e.g. FirstName, LastName), it is ignored. If your property name matches a parameter name (or Alias), it will pass that to the command. This is what the $CSV looks like:

FirstName LastName Path                           Destination                     
--------- -------- ----                           -----------                     
Rob       Simmers  C:\Users\Rob\Desktop\Archive\* C:\Users\Rob\Desktop\RobSimmers 
John      Smith    C:\Users\Rob\Desktop\Archive\* C:\Users\Rob\Desktop\JohnSmith  
Sam      Johnson  C:\Users\Rob\Desktop\Archive\* C:\Users\Rob\Desktop\SamJohnson

The fun part about this approach is you don't need a foreach loop, because it will be done with the Process inside the copy item function.

September 13, 2016 at 1:51 pm

Please disregard wrong forum venue

  • This reply was modified 2 years ago by  BrandonB. Reason: Delete this post please