powershell - 对 CSV Powershell 中的值进行数学运算

标签 powershell csv time

我有一个包含计划时间(一天)的 CSV,但值是从一天开始的毫秒数,我需要将值转换为一天中的时间(0:HH:mm:ss,fff)。这是 CSV 的外观:

"Log Date","Scheduled Time","Category","Cart #","Scheduled Title","Actual Title","Start Date","End Date","Scheduled Length","Actual Length"
"7/18/2018 12:00:00 AM","22439181","DCM","3172","BONCHE URBANO DIGITAL 201","BONCHE URBANO COMERCIAL JUN 23","12/31/1969 7:00:00 PM","12/31/9999 11:59:59 PM","30","33"
"7/18/2018 12:00:00 AM","45750000","DCM","3172","BONCHE URBANO DIGITAL 201","BONCHE URBANO COMERCIAL JUN 23","12/31/1969 7:00:00 PM","12/31/9999 11:59:59 PM","30","33"

我有这个,当我输入时间时,它可以工作:
("{0:HH:mm:ss,fff}" -f ([datetime]([timespan]::fromseconds($time / 1000)).Ticks))

如何使用它来替换 CSV 中的所有值?到目前为止,我有这个,但它不起作用,而且我对 Powershell 一开始就不是很好。
Import-Csv .\Values.csv | 
ForEach-Object {
$time = $_.'Scheduled Time'
$_.'Scheduled Time' = ("{0:HH:mm:ss,fff}" -f ([datetime]([timespan]::fromseconds($time / 1000)).Ticks));$_
} | 
Export-Csv '.\Values.csv' -NoTypeInformation

在此先感谢您的帮助!

最佳答案

iRon在对问题的评论中提供了关键指针:Import-Csv输出到 Select-Object调用,它可以通过 calculated properties 选择性地转换输入对象的属性 .

由于您想按原样保留其他属性,同时可能在不更改属性顺序的情况下执行转换,您必须明确枚举所有输出属性 ,这可能更容易通过预先构建一个数组来完成。

# Define the property names to extract from the imported rows,
# interspersed with the calculcated property to transfrom the 'Scheduled Time'
# column values:
$properties = 
  'Log Date',
  @{ 
     n='Scheduled Time'
     e={ '{0:HH:mm:ss,fff}' -f [datetime] ([timespan]::FromTicks([long] $_.'Scheduled Time' * 10000)).Ticks } 
  },
  'Category',
  'Cart #',
  'Scheduled Title',
  'Actual Title',
  'Start Date',
  'End Date',
  'Scheduled Length',
  'Actual Length'

# Import the CSV - by reading it into memory _in full_ first -, select the
# properties and perform the transformation, then write back to the file.
(Import-Csv ./Values.csv) | # !! The (...) are required
  Select-Object $properties |
    Export-Csv -NoTypeInformation ./Values.csv

注意需要附上Import-Csv来电(...)为了强制预先将其全部内容全部读取到内存中,这是能够作为同一管道的一部分写回同一文件的先决条件。
没有它,你基本上会删除文件。

除了对大输入文件的可用内存的担忧之外,还请注意,此方法带有 数据丢失的轻微风险 ,如果在将所有(转换的)对象写回输入文件完成之前中断管道。

更强大的解决方案是先写入临时文件,并在成功完成后用临时文件替换原始文件。

关于powershell - 对 CSV Powershell 中的值进行数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51402755/

相关文章:

python - VSCode/ Visual Studio Code : Unable to Load Conda Environment in VSCode Terminal

powershell - Stop-Service Cmdlet无法打开存在的服务

javascript - 让秒数自动更新?

parsing - 更改 time.Time 时区而不重新解析

c++ - Qt如何修改windows系统时间?

powershell - 在 powershell 中检索 NUnit 自定义属性

excel - powershell 无法向 Excel 图表添加多个图例条目(系列)

java - 将字符串数组的数组写入文件(txt、csv 等)

python - 将 csv 从 gcs 迁移到 postgresql

JavaCSV 未读取任何行