简体   繁体   English

使用Powershell导出到带有列的CSV

[英]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. 我正在尝试做一个简单的脚本,将文件名和所述文本文件的内容提取为CSV文件。 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. 我能够很好地提取所有信息,但不会将其拆分为CSV文件中的不同列。 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. 当我在excel中打开CSV文件时,所有内容都在第一列中,并且我需要将这两部分信息分成不同的列。 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. 我是Powershell的新手,似乎无法摆脱这个小小的减速。 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. 我担心如果文本导入在Excel中遇到问题。 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,但正在寻找文本导入向导。

Excel will treat the data in csv files which are delimited bij the ; Excel将以分隔的csv文件中的数据进行处理; as a single columns. 作为单列。 I always use the -delimiter switch on export-csv or convertto-csv to set this as a delimiter. 我总是在export-csv或convertto-csv上使用-delimiter开关将此设置为定界符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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