Powershell script to append an extension to a file, input from CSV

powershell

All I need is to have an Excel list of file paths and use Powershell to append (not replace) the same extension on to each file.

It should be very simple, right? The problem I'm seeing is that if I go import-csv -path myfile.csv | write-host I get the following output:

@{FullName=C:\Users\jpalumbo\test\appendto.me} 
@{FullName=C:\Users\jpalumbo\test\append_list.csv} 
@{FullName=C:\Users\jpalumbo\test\leavemealone.txt}

In other words it looks like it's outputting the CSV "formatting" as well.

However if I just issue import-csv -path myfile.csv, the output is what I expect:

FullName
--------
C:\Users\jpalumbo\test\appendto.me
C:\Users\jpalumbo\test\append_list.csv
C:\Users\jpalumbo\test\leavemealone.txt

Clearly there's no file called "@{FullName=C:\Users\jpalumbo\test\leavemealone.txt}" and a rename on that won't work, so I'm not sure how to best get this data out of the import-csv command, or whether to store it in an object, or what.

Thanks!!

Best Answer

Try this

$list=import-csv("myfile.csv")
foreach ($entry in $list) {
    $withExt=$entry.FullName+".txt"
    write-host $withExt
}

The tricky part is that import-csv returns an array of arrays essentially. This is why our first version is formatted the way it is, as what write-host is getting is a list of lists. You have to iterate over each line and treat each line individually. Or at least that's one way to do it.

Massimo has the one-liner on this one.