$txtpath = C:PowershellProjectsCreateReports eport.txtGet-Content $txtpath |ForEach-Object {if($_ -match DEFAULT){$filepath = Join-Path -Path (Split-Path $txtpath) -ChildPath (($_ -split )[3] + .dat
font-size: 10pt;">)
$_ | Out-File -FilePath $filepath -Encoding ASCII -Force
}
else
{
$_ | Out-File -FilePath $filepath -Encoding ASCII -Append -Force
}
}
The break down of this script is as follows:- line 1: $txtpath indicates the path to the file I want to parse.
- line 2: Get-Content from file at $txtpath and pass to the pipeline.
- line 3: Since Get-Content will return an array of strings I use Foreach-Object to parse each one
- line 4: Test to see if the current line matches DEFAULT. This is my page break.
- line 6: Set the filepath based on the original files directory path and a substrings value in the current line.
- line 7: Write the current line to the file. Using -Force overwrites existing files. In my case, this was fine.
- line 11: Write all other lines to the same file with -Append so as to not keep overwriting with a single line at a time. Again, -Force is used to ensure previous files are overwritten.