[英]Powershell script Export-CSV cutoff characters in a string of a .TXT files with Comma
1 .. $Count | ForEach-Object {
$i = $_.ToString($Length)
$Offset = $BatchSize * ($_ - 1)
$outputFile = $ParentDirectory + "\" + $strBaseName + "-" + $i + $strExtension
If($_ -eq 1) {
$objFile | Select-Object -First $BatchSize | Export-Csv $outputFile -NoTypeInformation -Encoding UTF8
} Else {
$objFile | Select-Object -First $BatchSize -Skip $Offset | Export-Csv $outputFile -NoTypeInformation -Encoding UTF8
}
}
I have a.txt with a comma on row 3 below.我在下面的第 3 行有一个带逗号的 a.txt。 My code is stripping anything after the comma as seen below.
我的代码在逗号之后删除任何内容,如下所示。 how do I fix it?
我如何解决它? My file is pipe delimited.
我的文件以 pipe 分隔。
|Header1|Header2|Header3|Header4|
|320|A1| |0900|
|320|A2|This, comma is needed|0900|
|320|A3| |0700|
|320|A4|f2|0900|
|320|A5| |0700|
|320|L2|c6|0900|
After splitting into 2 files -notice the missing text after "this,"分成 2 个文件后 - 请注意“this”之后缺少的文本,
file1文件1
|Header1|Header2|Header3|Header4|
|320|A1| |0900|
|320|A2|This,
|320|A3| |0700|
file2文件2
|Header1|Header2|Header3|Header4|
|320|A4|f2|0900|
|320|A5| |0700|
|320|L2|c6|0900|
Please advise.请指教。 Thanks
谢谢
I tried to use delimiter and replace commands.我尝试使用定界符并替换命令。 Didn't work
没用
It looks like when you imported your delimited file into $objFile
, you forgot to pass看起来当您将分隔文件导入
$objFile
时,您忘记了传递-Delimiter '|'
to the Import-Csv
call, which would not interpret your |
到
Import-Csv
调用,它不会解释您的|
-separated file properly, given that Import-Csv
- as well as Export-Csv
- default to ,
as the separator. - 正确分隔文件,因为
Import-Csv
- 以及Export-Csv
- 默认为,
作为分隔符。
Thus, the solution is to use -Delimiter '|'
因此,解决方案是使用
-Delimiter '|'
in both your Import-Csv
and Export-Csv
calls.在您的
Import-Csv
和Export-Csv
调用中。
As for what you tried :至于你尝试了什么:
Here's a minimal example that demonstrates the problem with omitting -Delimiter '|'
这是一个最小的示例,演示了省略
-Delimiter '|'
的问题, using the in-memory CSV processing cmdlets, ConvertFrom-Csv
and ConvertTo-Csv
: ,使用内存中的 CSV 处理 cmdlet、
ConvertFrom-Csv
和ConvertTo-Csv
:
@'
Field1|Field2
Value1|Value2, and more
'@ |
ConvertFrom-Csv |
ConvertTo-Csv
Output (note the missing , and more
part, and how the output lines as a whole are double-quoted): Output(请注意缺失
, and more
部分,以及整个output 行如何被双引号引起来):
"Field1|Field2"
"Value1|Value2"
Since header row Field1|Field2
contains no ,
it became a single property in the resulting objects, literally named Field1|Field2
.由于 header 行
Field1|Field2
不包含 no ,
因此它成为结果对象中的单个属性,字面上命名为Field1|Field2
。
Since the data row happened to contain ,
it was parsed as two fields, and since there is only one column, the extra field was simply discarded .由于数据行恰好包含
,
因此被解析为两个字段,而由于只有一列,所以多余的字段被简单地丢弃了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.