1

I have a number of .csv files that I need to modify to have 2 extra columns. 1 column is labelled 'site' and will be the same for all files in the same directory (0 in the example). The other is simply the original filename so that I can later merge these files but still preserve their original relationships.

I tried the following, but it just blanks out all the .csv files:

$files = Get-ChildItem ".\"

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    Import-Csv $files[$i].FullName | Select-Object *,@{Name='site';Expression={'0'}},@{Name='trace';Expression={$files[$i].FullName}} | Export-Csv $files[$i].FullName -NoTypeInformation
}
2
  • 1
    In your title, you say you need to add rows. In the post, you say you need to add columns. Please clarify - which is it? Commented May 6, 2014 at 17:48
  • It's columns, sorry. Edited. Commented May 6, 2014 at 18:02

1 Answer 1

1

How about something along these lines:

$files = Get-ChildItem ".\" -filter "*.csv"

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    $csv = Import-Csv $files[$i].FullName 
    $newcsv = @()
    foreach ( $row in $csv ) {
        $row | Add-Member -MemberType NoteProperty -Name 'site' -Value '0'
        $row | Add-Member -MemberType NoteProperty -Name 'trace' -Value $files[$i].FullName
        $newcsv += $row
    }
    $newcsv | Export-Csv $files[$i].FullName -NoTypeInformation
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Is there a way to just append the filename and not the full path?
Instead of .FullName you could use .Name in the Add-Member line
That makes sense. Thanks, I'm not very familiar with powershell.
Using Get-Member and Format-List can be helpful in digging some of this stuff up... For instance, Get-ChildItem foo.csv | Get-Member will list off of the methods and properties of a directory listing. Get-ChildItem foo.csv | Format-List * will display the values of the properties of that directory listing. (All of that assumes you have a file named foo.csv in your current directory, of course) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.