在CSV Powershell中对值进行数学运算



我有一个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调用,该调用通过计算的属性实现输入对象属性的选择性转换

由于您希望按原样保留其他属性,同时可能在不更改属性顺序的情况下执行转换,因此必须显式枚举所有输出属性,这可能更容易通过预先构造数组来实现。

# 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调用封装在(...)中,以便强制将其全部内容提前、完整读取到内存中,这是能够作为同一管道的一部分写回同一文件的先决条件
如果没有这一点,您基本上会擦除文件。

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

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

最新更新