Home > Software engineering >  powershell copy and delete files based on csv
powershell copy and delete files based on csv

Time:11-05

I have csv file with list of files and action column:

Filename Action
C:\postgres\1.tmp 1
C:\postgres222\2.txt 1
C:\postgres3333\3.jpeg 0

If action is 1 I need to recreate the same directory path on D:\, to copy file there and then to delete it from C:\. If action is 0, just ignore it. In example for above files I want to have 2 new files created on D:\ = copied from C:\ and on C:\ to have only 1 file 3.jpeg (because it has 0 in action)

D:\postgres\1.tmp 
D:\postgres222\2.txt 

CodePudding user response:

Supposing your csv file is named your_file.csv and the delimiter is a blank (" "):

Get-Content ./your_file.csv | 
    ConvertFrom-Csv -Delimiter " " | 
    Where-Object { $_.Action -eq 1 } | 
    ForEach-Object { 
      Copy-Item $_.Filename -Destination $_.FileName.Replace("C:", "D:") -Force 
    }

CodePudding user response:

It looks like your CSV file uses a space character as delimiter to separate the fields from each other. If in real life this is not the case, change the -Delimiter in the code below to match the character that is actually used (most common is the comma)

The below code will create the file path on the D:\ drive and then move the file to there.

Import-Csv -Path 'D:\Test\filelist.csv' -Delimiter ' ' | 
Where-Object { $_.Action -ne '0' } |
ForEach-Object {
    $originalDrive = [System.IO.Path]::GetPathRoot($_.FileName)         # --> C:\
    $originalPath  = [System.IO.Path]::GetDirectoryName($_.FileName)
    # construct the new path on the D:\ drive
    $targetFolder  = 'D:\{0}' -f $originalPath.Substring($originalDrive.Length)
    # or use: 
    # $targetFolder = Join-Path -Path 'D:\' -ChildPath $originalPath.Substring($originalDrive.Length)

    # create the target directory if this does not exist
    $null = New-Item -Path $targetFolder -ItemType Directory -Force
    # move the file from the original location to the target directory
    Move-Item -Path $_.FileName -Destination $targetFolder
}
  • Related