我在文本文件中有一组日期。
实施例。 file.txt的
2011-01-01
2011-02-14
2011-02-21
2011-03-17
2011-09-11
2011-11-11
我有一个名为Important-Dates
的函数,它包含[datetime]
个日期
实施例。函数包含这些类型的日期
November-11-15 12:00:00 AM
November-11-14 12:00:00 AM
November-11-13 12:00:00 AM
February-14-15 12:00:00 AM
我希望将函数日期转换为格式yyyy-mm-dd
并附加到file.txt文件
到目前为止,我有这个:
$Dates = Important-Dates
if ( -not (test-path 'file.txt' -pathtype leaf))
{
"{0:yyyy-MM-dd}" -f $Dates | Set-Content 'file.txt'
exit 1
}
else {
"{0:yyyy-MM-dd}" -f @($_.$Dates) | Add-Content 'file.txt'
exit 1
}
我得到的所有File.txt文件是重要日期列表中的第一个日期
"November-11-15 12:00:00 AM"
- 确实转换为2015-11-11
我想要所有日期。我做错了什么?
答案 0 :(得分:1)
向-f
提供集合只会使用集合中的第一个元素。您想要处理集合中的每个日期对象。
要处理集合中的每个对象,您可以使用foreach-object:
$Dates | ForEach-Object -Process { "{0:yyyy-MM-dd}" -f $_ } | set-content 'file.txt'
}
...或更简洁:
$Dates | % { "{0:yyyy-MM-dd}" -f $_ } | Set-Content 'file.txt'
答案 1 :(得分:1)
DateTime
个对象可以通过ToString()
方法进行格式化:
$Dates | % { $_.ToString('yyyy-MM-dd') } | Set-Content 'file.txt'