我使用以下ps命令批量读取文件夹中每个txt文件的内容,然后将其导出到csv。它正常读取,但是文件内容变成一行,所有换行符都丢失了。
ls |Select-Object -Property {Get-Content $_.FullName -Encoding utf8} | Export-Csv "a.csv" -Encoding UTF8
我希望它在导出时保持格式(主要是空格和换行符)。
输入和输出:在这里输入图像描述
发布于 2022-10-31 12:36:27
-Raw与Get-Content一起确保每个文件被读取为一个单一的、多行的string.Note。使用-Raw Get_ Select-Object -Property { Get-Content -Raw $_.FullName -Encoding }>导出-Csv "a.csv“-Encoding utf8。Get-Content不带-Raw,并使用-joinNote -join "n" (joining the lines with Unix-format LF-only newlines). # Each resulting string will have \*no\* trailing newline, but you # you can add it with ((Get-Content ...) -join "n") + "n" # Use "rn" for Windows-format CRLF newlines. Get-ChildItem | Select-Object -Property { (Get-Content $\_.FullName -Encoding utf8) -join "n“} Export-Csv "a.csv”-Encoding UTF8将生成的行数组与选择的换行符/序列连接起来。注意,您的CSV文件:
"..."-enclosed多行字符串。- Use something like `Select-Object Name, { ... }` to also include each file's _name_.Select-Object的-Property参数的{ ... })的逐字内容。- To give the column a better name, use a [hashtable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Hash_Tables) as the [calculated property](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Calculated_Properties), whose `Name` entry allows you to specify the name, and whose `Expression` entry must be your script block; e.g.:.‘>选择-Object @{ Name=’FileContent‘;Expression={ Get-Content -Raw $_.FullName -Encoding utf8 }}.
至于,你尝试过
-Raw时,Get-Content逐行地流文件的内容,当捕获该输出时,它将成为一个数组。Export-Csv (或ConvertTo-Csv)遇到作为数组(或类似类型的集合)的属性值时,它会将其收缩,即必须将集合的表示形式创建为单个字符串。- _Usually_, this results in _useless_ stringification simply by the collection's _type name_, e.g., in the case of an array, _verbatim_ `System.Object[]`- However, if - as in your case - the collection happens to be wrapped in a usually _invisible_ `[psobject]` instance, a more helpful, albeit single-line stringification occurs: the (stringified) collection elements are joined _with spaces_ in effect, the newlines from your file are therefore replaced with spaces.- The reason a `[psobject]` wrapper is present in your case is that PowerShell wraps output objects from a _pipeline_ that way - which includes output from a script block (`{ ... }`).为说明上述情况:
# NO [psobject] wrapper -> CSV serialization by *type name*:
PS> [pscustomobject] @{ ArrayProp = 'one', 'two' } | ConvertTo-Csv
"ArrayProp"
"System.Object[]" # !!# WITH [psobject] wrapper -> CSV serialization by
# *space-concatenated elements*:
PS> [pscustomobject] @{ ArrayProp = [psobject] ('one', 'two') } | ConvertTo-Csv
"ArrayProp"
"one two" # !!https://stackoverflow.com/questions/74261118
复制相似问题