在CSV Powershell中计算值

在CSV Powershell中计算值,powershell,csv,time,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","2243

我有一个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
提前感谢您的帮助

在对该问题的评论中提供了关键指针:
Import Csv
输出通过管道传输到
Select Object
调用,该调用可通过
选择性地转换输入对象的属性

由于您希望保持其他属性不变,同时假定在不更改属性顺序的情况下执行转换,因此必须显式枚举所有输出属性,,通过预先构造数组,这可能更容易做到

# 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
请注意,需要将
导入Csv
调用包含在
(…)
中,以便强制将其全部内容提前读取到内存中,这是能够作为同一管道的一部分写回同一文件的先决条件。

如果不这样做,您将基本上删除该文件

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


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

使用如下属性表达式:
@{Name=“Scheduled Time”;expression={({0:HH:mm:ss,fff})-f([datetime]([timespan]::fromseconds($Time/1000)).Ticks}
谢谢您的帮助!