0

I am using PowerShell to dump some reports to CSV, and I would like to limit the size of the reports. When a report is generated I use...

Export-Csv -Path [path] -Append -NoTypeInformation

...which creates a file with a single header line, which is what I want. The issue is, as I add records, I would like to limit the file to the 1000 newest rows. So for instance if I have 1300 rows, how do I keep the header and get rid of lines 1-300 of data?

4
  • 1
    Either you create only 1000 lines of the report (how do you create the report?) you could use a Select-Objectbefore exporting the data to csv file, or you output the csv data again and use a Select-Object with par example a -First 1000 or -Last 1000 to recreate the csv. Commented Mar 7, 2018 at 20:52
  • The issue is that I add to the report, for instance 100-200 records at a time, so limiting the export really won't work. I was looking for a way to export and append the csv, then remove any overage lines. Commented Mar 7, 2018 at 20:55
  • So if you have all lines collected you output the data again and recreate it with the parameter I mentioned above. Commented Mar 7, 2018 at 20:56
  • I agree with @Olaf - the -Append parameter of Export-Csv is inefficient as the file gets larger and it is good to avoid using it if possible. Commented Mar 7, 2018 at 21:12

1 Answer 1

3

If you cannot limit the number of lines while creating the reports you can import the data from the csv file and export it again while limitting to last or first 1000 ... like this:

Import-Csv -Path 'path to your csv file' | 
    Select-Object -Last 1000 |
        Export-Csv -Path 'path to your final csv file' ... more parameter if needed
Sign up to request clarification or add additional context in comments.

5 Comments

OK, that's just way easier than I was making it.
OK, here is the code. It's still just creating a blank csv file for some reason. Import-Csv -Path "$reportPath\$($user).csv" | Select-Object -Last 6 | Export-Csv -Path "$reportPath\$($user).csv" -NoTypeInformation
I used "last 6" just for testing purposes.
OK, I am baffled. If I assign the Import-Csv segment and Select-Object segment to an object, then Export-Csv, it works. If I just pipe it into Export-Csv, it results in a blank file. Any idea why?
What do you mean with "assign to an object"? If I run the snippet it works just as expected.

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.