Elroy Taulton
Elroy Taulton

Reputation: 5

How to read values from a CSV file and use them to rename a file in PowerShell

I have a pdf file test.pdf and a TXT/CSV file CSVTest.txt. I am trying to take the values from the TXT/CSV ("1234", "this", "file") and within PowerShell rename the test.pdf to 1234_this_file_test.pdf. I cannot figure out how to get this to work. Here is what I have so far

$files = "C:\Work\SouthParchment"

$temp = Import-Csv "C:\Work\SouthParchment\CSV\*.txt"

#$files - ls*.csv


$files |ForEach-Object{
    $fullname = $_.FullName 
    Write-Output $fullname
    #$temp = Import-Csv $_.FullName -Delimiter ";"
    $temp = Import-Csv "C:\Work\SouthParchment\CSV\*.txt" -Delimiter ";"
    $newname = ($temp|select -first 1)."Document Type" + ".pdf"
    #Rename-Item -Path $fullname -newname $newname -WhatIf
    Rename-Item $fullname -newname $newname -WhatIf

}

Upvotes: 1

Views: 138

Answers (1)

Abraham Zinala
Abraham Zinala

Reputation: 4694

To answer your immediate question, concatenating the columns using -join will give you the new name you're after based off the imported csv:

$path = "C:\Work\SouthParchment"
Import-Csv -Path "$path\*.txt" -Header "one","two","three" | 
   ForEach-Object -Process {
        $newName = $_.PSObject.Properties.Value -join "_"
        Rename-Item -Path "$path\*.pdf" -NewName $newName -WhatIf
    }

The issue comes with the following...

  1. Randomness - the way you're calling your csv, and then renaming your pdf, you're assuming there is only one csv, and one pdf in your current directory.

  2. The next would be the rows in your csv. You say you plan on doing this for more pdf's but, how will it know which one to do next?

    • In other words, there is nothing to disambiguate one pdf from the next.
    • No means of saying which pdf should be named what from what row in the csv.

Would suggest looking into my bullet points and coming up with a better solution on how to implement this.

Upvotes: 1

Related Questions