powershell move files based on csv contents

Tagged: , , , ,

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Richard Deans Richard Deans 3 years ago.

  • Author
    Posts
  • #16463
    Profile photo of Richard Deans
    Richard Deans
    Participant

    Hi All and thanks for helping!

    I have produced a set of PDF files which are all saved in

    L:\ClientSort\

    Each of these files has a naming convention in the following way

    XXX_A123456_YYY.PDF
    XXX_300123123_YYY.PDF

    (the xxx stands for the brand)
    the yyy stands for account type)

    What I need to do is move these PDF's into one of two directories based on criteria within a CSV, excel or text file.

    I will perform the logic of where the files should be sent within this file and within column D provide the file location to which I want to move the PDF.

    Please see the attached spreadsheet to further clarify this point.

    Basically... If the PDF naming convention contains the account number in column A, I need to move the file to the location specified in column D.

    I have looked at as many different solutions as possible and the closed I could find was
    [Link to poss solution][1]

    Anyone have any ideas how this may be achieved?

    Regards

    Richard

    [1]: http://stackoverflow.com/questions/23356289/powershell-script-to-move-files-based-on-a-source-list-txt

  • #16465
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Something along these lines should work:

    $moveTargets = @{}
    
    $csvFile = '.\ClientDataSort.csv'
    $sourceFolder = 'L:\ClientSort'
    
    foreach ($record in Import-Csv -Path $csvFile)
    {
        $moveTargets[$record.AccountRef] = $record.FileSortLocation
    }
    
    Get-ChildItem -Path $sourceFolder |
    ForEach-Object {
        $pdfFile = $_
        if ($pdfFile.Name -match '^[^_]*_([^_]*)_[^_]*\.pdf$')
        {
            $accountRef = $matches[1]
            $target = $moveTargets[$accountRef]
    
            if ($target)
            {
                Move-Item -Path $pdfFile.FullName -Destination $target
            }
        }
    }
    
  • #16466
    Profile photo of Richard Deans
    Richard Deans
    Participant

    Thank you so much, I am going to have a try with this... I am starting out with powershell and it's coding convention is baffling me so far. I am sure it will get easier!

    I had used some of this coding in my build so far, reassuring it's on the right path!

    I'll let you know how I get on...

    Regards

    Richard

  • #16468
    Profile photo of Richard Deans
    Richard Deans
    Participant

    Spot on... Thanks so much!

You must be logged in to reply to this topic.