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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我们如何使用Windows Powershell脚本替换文本文件中的日期?相关的知识,希望对你有一定的参考价值。

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

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

我想要实现的步骤:

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

我刚刚编写了这段代码:

$path = "C:PSFilesRec_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

请帮忙吗?

答案

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

剧本:

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

#replace old format
Get-Content -ReadCount 500 -Path C:PSFilesRec_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_outputRec_File_001.txt

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

另一答案
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

以上是关于我们如何使用Windows Powershell脚本替换文本文件中的日期?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用PowerShell管理Windows服务

使用Powershell管理Windows计划任务

如何在Windows服务器上新建一个Powershell.ps1的定时任务

电脑密钥如何获取??

如何在 powershell 中使用变量调用命令?

使用Powershell配置Windows Failover Cluster群集