How to change date format in multiple text files in powershell?

2

Hello I have around 5000 text files (TXT) in one directory.Files are comma delimited. What I'm trying to do is to change date format (it is stored in first column of each file) from M/d/yyyy to MM/dd/yyyy. There is around 1 milion lines in those 5000 files so I hope there is some efficient way to do it.I read somewhere that for handling such a big number of data a StreamWriter command is a way to go, but I'm not sure if it can be used in my case. Thank you for any suggestion.

I'm using this script for deleting second and last row of multiple text files using StreamWriter. It is very fast and efficient. I hope that with some small modifications it can be used for changing date formats in first column. I have just 2 weeks experience with PS so this is quite a challenge for me.

dir *.txt | %{     
$content = gc $_.FullName
$output = @($content | select -First 1 )
$output += $content[2..($content.count -2)]
$sw = New-Object System.IO.StreamWriter($_.FullName,$false)
$output | %{$sw.WriteLine($_)}
$sw.close()
}

paul

Posted 2015-02-05T16:41:44.563

Reputation: 21

1What have you researched or attempted so far? Can you share any scripts you have been working with? – CharlieRB – 2015-02-05T17:26:31.680

Answers

0

You say your text files are comma delimited. Well, you could use Import-Csv -Path C:\file.txt. Then PowerShell makes each row into an object. Objects are easier/more accurate to manipulate than text. Objects might be "slower" but 5000 files/ 1M lines are nothing even for a cheap laptop. Not sure how PS would handle the 1st and last lines of your files, since I don't know the format.

Converting the dates are easy. If I give Get-Date a date string formatted like m/d/yyyy, I use the -UFormat parameter to format the date however I want. Get-Help Get-Date -Full

PS> Get-Date 2/8/2016 -UFormat "%m/%d/%Y"
02/08/2016

E.V.I.L.

Posted 2015-02-05T16:41:44.563

Reputation: 218