Monday, September 26, 2016

PowerShell v2 Generate Files from Single Doc Based on Header

This one is hard to title accurately. We have raw reports in a single file that are broken up by "headers". This can mean different things to different people, but, in my case, it was something I could test for.  So, in my initial design of the script I started looking for a regular expression.  Yet, after putting something on the forums, Justin Rich helped me come up with a simple way to handle the scenario.
$txtpath = C:PowershellProjectsCreateReports eport.txt
Get-Content $txtpath |
ForEach-Object {
      if($_ -match DEFAULT)
      {
            $filepath = Join-Path -Path (Split-Path $txtpath) -ChildPath (($_ -split )[3] + .dat)
            $_ | 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:

  1. line 1: $txtpath indicates the path to the file I want to parse.
  2. line 2: Get-Content from file at $txtpath and pass to the pipeline.
  3. line 3: Since Get-Content will return an array of strings I use Foreach-Object to parse each one
  4. line 4: Test to see if the current line matches DEFAULT. This is my page break.
  5. line 6: Set the filepath based on the original files directory path and a substrings value in the current line.
  6. line 7: Write the current line to the file. Using -Force overwrites existing files. In my case, this was fine.
  7. 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.

Related Post:

0 comments:

Post a Comment

 
Copyright 2009 Information Blog
Powered By Blogger