Search code examples
powershellpowershell-3.0

Export content of multiple files to a CSV


Im trying to export the content of multiple .log files into a single CSV.

I think I'm close, but I just can't figure out what I'm doing wrong. I'm guessing it's somewhere in the foreach:

$dir = "\\server\c$\folder1\folder2"
$filter = "*.log"

$files = Get-ChildItem -path $dir -filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 10

foreach ($file in $files){
Get-Content $file | convertTo-csv | export-csv -path "\\server\share\test.csv"
}

I've tried to write the get-content line in so many ways, but none seem to work.

When I do $files.name, it lists up the files perfectly.

The error I get from the code is "Cannot find path 'C:\Users\Myname\filename1.log' because it does not exist.. I don't understand why, because I never spesified the c:\users path..


Solution

  • You can simply use the Import-CSV cmdlet to load the CSV instead of the Get-Content and convertTo-csv cmdlet:

    $files = Get-ChildItem -path $dir -filter $filter | 
        Sort-Object LastAccessTime -Descending | 
        Select-Object -First 10 | 
        Select-Object -ExpandProperty FullName
    
    Import-Csv -Path $files | Export-Csv "\\server\share\test.csv"