我们如何使用Windows Powershell脚本替换文本文件中的日期?

问题描述 投票:0回答:2

我正在编写一个windows powershell脚本来打开/编辑文本文件。

它有许多记录,每个记录都以逗号分隔值(csv)排序:

我想要实现的步骤:

  1. 打开服务器A上的目录中的文本文件。
  2. 使用“当前日期”或其他编辑“日期”字段。
  3. 将相同的文本文件保存在同一位置(文件夹)。
  4. 将所有文件复制到不同服务器B中的新文件夹。

我刚刚编写了这段代码:

$path = "C:\PSFiles\Rec_File_001.txt" 
$Filedata = Get-Content $path
$Record01 = $Filedata[0].split(",")
$Record01Date = $Record01[3]
$Record01CurrentDate = Get-Date -format yyMMdd
$Record01 -replace $Record01Date, $Record01CurrentDate
Set-Content $path

请帮忙吗?

arrays windows shell powershell automation
2个回答
1
投票

你在这里有多个问题。我将解决标题中显示的那个 - 替换文本文件中的文本。

剧本:

# current date in a new format
$CurrentDate = Get-Date -format yyMMdd

#replace old format
Get-Content -ReadCount 500 -Path C:\PSFiles\Rec_File_001.txt | % {$_ -replace "(0[1-9]|1[012])\d{1,2}(0[1-9]|[12][0-9]|3[01])", "$CurrentDate"} | Set-Content -Path C:\PSFiles_output\Rec_File_001.txt

这需要regexp作为日期格式Date(mmYYdd)并将其换成新的格式。选项-ReadCount限制一次通过管道的行数。


0
投票
Import-CSV $Path -header text1, text2, text3, date, text5 | 
Select text1, text2, text3, @{Name="Date"; Expression={Get-Date -format yyMMdd}}, text5 |
ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1 |
Set-Content $Path

要么:

$data = Import-CSV $Path -header text1, text2, text3, date, text5
$data | ForEach {"Date" = Get-Date -format yyMMdd}
$data | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content $Path
© www.soinside.com 2019 - 2024. All rights reserved.