Powershell Scripting – How to Replace a Line or Date in a Text File

powershellregexscripting

I am trying insert today's date on a text file at line 59. How do i do this?

Line 59 has like 30 spaces and then reads like this. After the PowerShell script runs it will change the date so it has to be something that doesn't look for the date on the file.

                                Rep.Setproperty "Date","1/1/2013"

I want to just change the date to the date I run the PowerShell script. The text file it is not a PowerShell script so.

This is something that has to run every week with no user interaction. that is why we need the date change by a PowerShell script. I had looked up the link you provided but I am stuck that is why I posted here. there are two things I still can do.

  1. Replace the date at line 59
  2. Send today's date to replace whatever was there.

this is what i have so far.

$date = Get-Date
$CMSReport = Get-content C:\reports\CMSReport.acsauto
$CMSReport | ForEach-Object {
    if ($_.Readcount 59) {
        $_ -replace '\w+','Rep.SetProperty "Dates","2/4/2013"'
    } else {
        $_
    }
} |
Set-Content testCMS.acsauto

obviously the "2/4/2013" will have to be changed with some kind of variable that will take the date of when the command is run.

Best Answer

Why use PowerShell for a one-time string match/replacement? If this is something you need to do repeatedly across a bunch of files or replace multiple times in a single file, then that's different, but it'd probably take you longer to make the script to do this than to do a one-time replacement (or even twenty of them).

In any case, what you need is going to be found here:

https://blogs.technet.com/b/heyscriptingguy/archive/2008/01/17/how-can-i-use-windows-powershell-to-replace-characters-in-a-text-file.aspx?Redirected=true

Rigged into your scenario:

$infile = "C:\myinputfile.txt"
$outfile = "C:\myoutputfile.txt"
$content = Get-Content -Path $infile
$content[58] = $content[58] -replace "([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d", [datetime]::Today.ToShortDateString()
$content | Set-Content $outfile
Related Topic