TheCodeLab
TheCodeLab

Reputation: 49

Powershell how to loop through individual files in a directory

I have a directory containing text files that I need to loop through and remove the first and last line in each file. After that I need to concatenate them and set the output to one file.

My issue is when I loop through the directory it is only manipulating the first file and then stopping. How can I go through each one?

My code:

$path = 'C:\RemoveFirst\*.txt'
$output = 'C:\RemoveFirst\Work.txt'

for ($i = 0; $i -lt $path.Count; $i++) {
    Get-Content $path | Select-Object -Skip 1 | Select-Object -SkipLast 1 | Set-Content $output
}

Upvotes: 0

Views: 1623

Answers (2)

zett42
zett42

Reputation: 27806

This should do the trick:

$path = 'C:\RemoveFirst\*.txt'
$output = 'C:\RemoveFirst\Work.txt'

Get-Item $path | ForEach-Object {

    # Output all except first and last line of current file 
    Get-Content $_ | Select-Object -Skip 1 | Select-Object -SkipLast 1

    ''  # Output an empty line at the end of each file

} | Set-Content $output
  • Get-Item loops over all matching elements when the path contains a wildcard.
  • The ForEach-Object makes the Select-Object statements operate on each file separately. Otherwise they would be applied to the concatenated stream of lines from all files, thus skipping only the 1st line of the 1st file and the last line of the last file.
  • Finally use Set-Content to concatenate all lines into a single file. Alternatively use Out-File, see this post for differences.

Upvotes: 0

Santiago Squarzon
Santiago Squarzon

Reputation: 61323

This works too:

$path = 'C:\RemoveFirst\*.txt'
$outfile = 'C:\RemoveFirst\Work.txt'

Get-ChildItem $path|foreach-object{
    Get-Content $_|select-object -Skip 1|select-object -SkipLast 1
} > $outfile

Upvotes: 1

Related Questions