简体   繁体   中英

Using Powershell to export to CSV with columns

I am trying to do a simple script that pulls in the name of the file and the contents of said text file into a CSV file. I am able to pull in all of the information well enough but it's not splitting up into different columns in the CSV file. When I open up the CSV file in excel everything is in the first column, and I need the two bits of information separated into separate columns. So far my working code is as follows:

$Data = Get-ChildItem -Path c:path -Recurse -Filter *.txt |
where {$_.lastwritetime -gt(Get-Date).addDays`enter code here`(-25)}

$outfile = "c:path\test.csv" 
rm $outfile

foreach ($info in $Data) {
    $content = Get-Content $info.FullName
    echo "$($info.BaseName) , $content" >> $outfile
}

I figured out how to seperate the information by rows but I need it by columns. I'm new to powershell and can't seem to get past this little speed bump. Any input would be greatly appreciated. Thanks in advance!

Output:

Itm# , TextContent

Itm2 , NextTextContent

What I need:

Itm# | Text Content | 

Itm2 | NextTextContent |

Do you mean something like this?

Get-ChildItem -Path C:\path -Recurse -Filter *.txt | 
  Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-25) } | ForEach-Object {
  New-Object PSObject -Property @{
    "Itm#" = $_.FullName
    "TextContent" = Get-Content $_.FullName
  } | Select-Object Itm#,TextContent
} | Export-Csv List.csv -NoTypeInformation

Except for a few syntactical errors your code appears to be working as expected. I worry if you are having issues in Excel with you text import. I touched up your code a bit but it is functionally the same as what you had.

$Data = Get-ChildItem -Path "C:\temp" -Recurse -Filter *.txt |
    Where-Object {$_.LastWriteTime -gt (Get-Date).addDays(-25)}

$outfile = "C:\temp\test.csv" 
If(Test-Path $outfile){Remove-Item $outfile -Force}

foreach ($info in $Data) {
    $content = Get-Content $info.FullName
    "$($info.BaseName) , $content" | Add-Content $outfile
}

I don't know what version of Excel you have but look for the text import wizard.

Excel will treat the data in csv files which are delimited bij the ; as a single columns. I always use the -delimiter switch on export-csv or convertto-csv to set this as a delimiter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM