【发布时间】:2020-03-04 20:20:23
【问题描述】:
我找到了这段代码:
$csv = Import-Csv D:\ExcelFiles\ba.csv
$csvout = "D:\ExcelFiles\bas.csv"
$csv | ForEach-Object {
# Do the math
$_.result = [math]::round($_.A / $_.B, 0)
# Output the object (which contains A, B and result)
$_
} | Export-Csv $csvout -NoTypeInformation
如您所见,它仅适用于导入的 csv 文件。多csv文件怎么做这个操作?
编辑1:
我已经使用了这个代码:
$SourcePath = "D:\CsvFiles"
$CsvFiles = Get-ChildItem -Path $SourcePath -filter "*.csv"
foreach ($File in $CsvFiles)
{
$OutFile = "D:\CsvFiles\" + "\" + $File.BaseName + "s" + $File.Extension
$File | ForEach-Object
{
$_.result = [math]::round($_.A / $_.B, 0)
# Output the object (which contains A, B and result)
$_
} | Export-Csv $OutFile -NoTypeInformation
}
但它要求:
cmdlet ForEach-Object at command pipeline position 1
Supply values for the following parameters:
为了防止这种情况,我更改了如下代码(foreach 对象后的括号位置):
$SourcePath = "D:\CsvFiles"
$CsvFiles = Get-ChildItem -Path $SourcePath -filter "*.csv"
foreach ($File in $CsvFiles)
{
$OutFile = "D:\CsvFiles\" + "\" + $File.BaseName + "s" + $File.Extension
$File | ForEach-Object {
$_.result = [math]::round($_.A / B, 0)
# Output the object (which contains A, B and result)
$_
} | Export-Csv $OutFile -NoTypeInformation
}
这一次,我得到了这个错误:
在此对象上找不到属性“结果”。验证该属性是否存在并且可以设置。
谢谢。
【问题讨论】:
-
所有的csv文件都在同一个目录下吗?你试过什么?您是否考虑将上述内容包装在另一个
foreach循环中? -
请注意,这是“银行家的四舍五入”。奇数向上取整,事件数向下取整。
标签: powershell csv