【发布时间】:2016-08-09 07:15:14
【问题描述】:
我有许多 .txt 文件,这些文件是在几天的 handle.exe 运行中输出的。我需要重新组织数据以将其放入关系数据库。我需要做的第一件事是重新格式化日期。
每个文件有超过 800 个日期,在整个文件中分配不均。日期格式:
June 29, 2016 12:05:45 PM 我需要06-29-16 12:05:45。
我现在只处理一个文件,以便拨入。我尝试用Get-Date 替换原位日期(使用数组作为原始日期),但一无所获。然后我尝试了-replace,但没有成功。
我在这上面花了 3 或 4 天,但我想我的脑袋坏了。我已经尝试了很多东西的排列方式,以至于我现在都不知道自己在哪里了。
我尝试的最后一件事是在下面。尝试使用哈希表,表中包含旧日期和新日期。
##To set "|" as separator for arrays
$OFS = '|'
##To get original dates into array
$a = @(sls .\hp.txt -pattern '(june 29|june 30|july 1|july 2|july 3|july 4)' | select -ExpandProperty line)
##To get dates with corrected format into array
$b = @($a | foreach {$_ | Get-Date -Format "MM-dd-yy hh:mm:ss"})
##To get old and new dates into hash table
$dates = @{$a = $b}
##To bring in content from file
$file = (Get-Content C:\hp.txt)
##To replace "NAME" with "VALUE" from hash table into file
foreach ($d in $dates) {
$file = $file -replace $d.Name, $d.Value
}
##To save corrected file with new file name
Set-Content -Path C:\hpnew.txt -Value $file
$a 数组包含(一小部分):
2016 年 6 月 29 日 12:04:51 PM 2016 年 6 月 29 日 12:05:58 下午 2016 年 6 月 29 日 12:07:00 [注意:这里有更多日期] 2016 年 6 月 30 日 12:01:17 2016 年 6 月 30 日 12:02:19 2016 年 6 月 30 日 12:04:22 [注意:继续结束]
$b 数组包含:
06-29-16 12:04:51 06-29-16 12:05:58 06-29-16 12:07:00 [注意:更多日期] 06-30-16 12:01:17 06-30-16 12:02:19 06-30-16 12:04:22 [注意:继续结束]
可能有一个更简单、更优雅的解决方案。但任何帮助/指导都会很棒。
【问题讨论】:
-
如果你可以安装 PS v5 你可以试试 - Convert-FromString powershellmagazine.com/2014/09/09/…
-
基兰...谢谢你的小费。但是在 4.0 中真的没有办法做到这一点吗?哈希表会不起作用吗?看起来我已经接近了,但我无法做出最后的调整来让它踢出我想要的结果。