TechBaba
TechBaba

Reputation: 49

How to get filename with the content of the file in PowerShell

I have around 50 files that I was to consolidate into one with filename and then the content of that file and then leave one line maybe a dotted line after output of the file for e.g. it should look like this

File name -ABC
xxxxxxxxxxxxxxxx (Content of the file)
..................... (dotted line after output)
File Name - CDE
xxxxxxxxxxxx  (Content of the file)
...................
Get-ChildItem C:\temp | Get-Content

This script gives me the output not not in the format I want. I can't find a way to get the name of the file.

Upvotes: 2

Views: 9468

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

What you want is fairly trivial. You just need a ForEach-Object loop to process each input file individually and the format operator (-f) to inject your data into a template string:

Get-ChildItem 'C:\temp' | ForEach-Object {
  @'
File name - {0}
{1}
.....................
'@ -f $_.Name, (Get-Content $_.FullName -Raw)
} | Out-File 'C:\path\to\output.txt'

Upvotes: 8

Related Questions