Pepe_Fuego Pepe_Fuego - 4 months ago 26
PowerShell Question

Powershell loop for splitting mutiple txt files into seperate files

I'm having an issue looping through all files in the directory and splitting it according to the field "[IMPORT]"

Directory: \C\users$\Pepe\Desktop\TestInfoFolder

I have the following two files in the directory:
TestingInfo1.txt
TestingInfo2.txt

They look like this:

TestingInfo1.txt

[IMPORT]
1
2
3
4
5
6
7
8
9
10
[IMPORT]
11
12
13
14
15
16
17
18
19
20


TestingInfo2.txt

[IMPORT]
21
22
23
24
25


Desired Results would be 3 separate files split the string "[IMPORT]" this is included in the files.

Results 1:

[IMPORT]
1
2
3
4
5
6
7
8
9
10


Result 2:

[IMPORT]
11
12
13
14
15
16
17
18
19
20


Results 3:

[IMPORT]
21
22
23
24
25


Current Code:

$Path = "\\C\users$\Pepe\Desktop\TestInfoFolder"
Get-ChildItem $Path | foreach-object {
$InputFile = $_.FullName
$Reader = New-Object System.IO.StreamReader($InputFile)
$N = 1

While (($Line = $Reader.ReadLine()) -ne $null) {
if ($Line -match "[IMPORT]") {
$OutputFile = $matches[0] + $N + ".txt"
$N++
}

Add-Content (Join-Path $Path $OutputFile) $Line
}
}


The issue with the current query is that it appends the results of TestingInfo2.txt in the results of Results 1. Please let me know if you need any further clarification.

Answer

I would do it like this:

$SourcePath = "C:\Users\jon_dechiro\Desktop\Test"
$OutputPath = "C:\Temp"
$Count = 1
foreach ($File in (Get-ChildItem -Path $SourcePath -File))
{
    $FileRawContents = Get-Content $File.FullName -Raw
    foreach ($Import in ($FileRawContents -split '\[IMPORT\]'))
    {
        if ($Import -match '\d')
        {
            "[IMPORT]$Import" | Out-File "$OutputPath\Results$Count.txt"
            $Count++
        }
    }
}

That opens each file and splits by [IMPORT] and then sends each result to the output files as you indicated. Of course change the $SourcePath and $OutputPath variables to be what you need.