Home > Blockchain >  How do I get from a csv file only the value of the selected element, but from a different column?
How do I get from a csv file only the value of the selected element, but from a different column?

Time:04-09

I have this example of csv file:

NAME PATH
file 1 C:\path1
file 2 C:\path2
file 3 C:\path3

I also have a origin folder which contains files. The idea here is to see if the files in the CSV file exist in the folder and in the destination paths defined in the csv file. If they don't exist, there's nothing to do. If they exist, the script needs to copy them in the path defined in the value PATH of the csv file. So it basically it will rewrite an existing file.

I really hope the definition of the problem is clear. What I have until now is this:

$filesInfo = @(Import-Csv C:\files.csv)
$files = $filesInfo.NAME
$paths = $filesInfo.PATH

foreach ($file in $files){
    $isThereOrigin = Test-Path -Path "C:\folder\$file"
    if ($isThereOrigin){
        foreach ($path in $paths) {
            $isThereDestination = Test-Path -Path "$path\$file"
            if ($isThereDestination){
                    Copy-Item -Path "C:\folder\$file" -Destination $path
            }
        }
    }
}

So, basically, what I'm trying to do with this code is that first of all I try to see if the file exists in the origin folder. If there is file there, I see if there's a destination (because it may be the case that the destination file is not there). If both conditions are true, the file is copied. This works correctly.

However, there is a case where this code doesn't work. Let's say the the file2 is contained in path1 and path2. With the code I have now, the file2 is going to be copied in path1 and path2 and I don't want that. I want file2 to be copied only in the path defined in the csv file.

I hope it's clear. Thanks!

CodePudding user response:

Your mistake is in splicing the original array of row-like objects into two separate arrays:

$files = $filesInfo.NAME
$paths = $filesInfo.PATH

Instead, loop over the original $filesInfo array:

foreach ($fileInfo in $filesInfo){
    $fileName = $fileInfo.NAME
    $isThereOrigin = Test-Path -LiteralPath "C:\folder\$fileName"
    if($isThereOrigin){
        $path = $fileInfo.PATH
        $isThereDestination = Test-Path -LiteralPath "$path\$fileName"
        if($isThereDestination){
            Copy-Item -LiteralPath "C:\folder\$fileName" -Destination $path -Force
        }
    }
}
  • Related