2

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!!

0

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.

| improve this answer | |
  • I think i got it based on your answer: $list=import-csv("append_list.csv") foreach ($entry in $list) { $withExt=$entry.FullName+".txt" rename-item -path $entry.Fullname -newname $withExt -whatif } Thanks!! – Jeremy Jun 15 '10 at 18:36
1

Try this:

Import-Csv -path myfile.csv | ForEach-Object { Write-Host $_.FullName }

You can of course do anything you want in the script block of ForEach-Object, instead of just writing out the value of the "FullName" field.

This will append the ".ext" extension to all filenames:

Import-Csv -path myfile.csv | ForEach-Object { Write-Host $_.FullName + ".ext" }

The trick here is:

1) Use ForEach-Object in order to act on the actual objects created by Import-Csv.
2) Use $_.FieldName to refer to the value of a given field in each object (corresponding to the value of the field with the same name in the imported CSV file).

| improve this answer | |
  • Hi All, Thank you so much for a quick reply. When I run Import-Csv -path myfile.csv | ForEach-Object { Write-Host $_.FullName + ".ext" }, the output is the fullname of the file plus " + .ext"). For example, c:\test\foo.bar becomes "c:\test\foo.bar + ext". Is there a simple fix for this? Thank you!! – Jeremy Jun 15 '10 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.