Fler
Fler

Reputation: 392

Powershell - Find & Replace Dates

I'm looking for a bit of assistance here. I currently have a Powershell script which adjusts the dates within a file. I'm looking to stop myself having to manually adjust these dates every time. What I need is to replace the date two days ago, with the date from yesterday.

I believe that I'd have to use (Get-Date).AddDays(-1) and (Get-Date).AddDays(-2) but I'm not exactly sure how I'd script this in!

What I currently have:

echo "Adjusting Import Dates"

(Get-Content D:\Temp\Example.txt).replace('20180917', '20180918') | Set-Content  D:\Temp\Example.txt

Upvotes: 0

Views: 132

Answers (1)

Palle Due
Palle Due

Reputation: 6292

You could try this:

$yesterday = (Get-Date).AddDays(-1).tostring("yyyyMMdd")
$twodaysago = (Get-Date).AddDays(-2).tostring("yyyyMMdd")
(Get-Content D:\Temp\Example.txt).replace($twodaysago, $yesterday) | Set-Content D:\Temp\Example.txt

You just introduce variables for the two dates and format them to the required date format. There is probably some other way of replacing in files, but the above should work.

Upvotes: 3

Related Questions