Henrik Rosqvist
Henrik Rosqvist

Reputation: 93

Powershell - merge .txt files into one - based on modified date

I have a folder with thousands of files

File1:

A B C

A B C

File 2:

1 2123

2345

ResultFile (output):

A B C

A B C



1 2123

2345

How can I merge those into one file - with some space between each file-content? I also want just those files modified today

This is what I have now

Get-ChildItem H:\myFolder-include *.txt -rec | ForEach-Object {gc $_; ""} |  out-file H:\test.txt

How can I add the date-condition in here?

Upvotes: 0

Views: 486

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Use the Where-Object cmdlet to filter data passed along the pipeline:

$startOfToday = (Get-Date).Date
Get-ChildItem H:\myFolder-include *.txt -Recurse | Where-Object LastWriteTime -gt $startOfToday | ForEach-Object {$_ |gc ; ""} | Out-File H:\test.txt

Upvotes: 1

Jonathan Waring
Jonathan Waring

Reputation: 241

If you only want files that have been modified today, you would put a Where-Object into your code before the ForEach-Object section

Get-ChildItem H:\myFolder-include *.txt -rec |
Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)} | 
ForEach-Object {gc $_; ""} | out-file H:\test.txt

That would filter out files that have not been modified in the last day before they go into the foreach loop.

Upvotes: 0

Related Questions