4/8/10

PowerShell File Concatenation Script

Concatenates text files into a single file for printing, text-zip-attachments, etc.
File index is included at the top of the output file.
function concatFiles($outFile)
{
  begin
  {
    $date = get-date
    [string[]] $filelist = @()  #empty string array
    $filebreak = '-'*32
  }
  process
  {
    #for process-block vars, append data using +=
    $_.fullname  #or "$_", console - show file name
    $filelist += $_.fullname
    $filedata += "$filebreak`nfile: $_`n"
    $filedata += gc $_.fullname | out-string  #use out-string to restore linebreaks
  }
  end
  {
    $filecount = $filelist.length
    "{0} files" -f $filecount  #console - show file count
    $fileheader = "{0}`n" -f $date.toString('MM-dd-yy HH:mm:ss')
    $fileheader += "concat output file: {0}`n{1} files" -f $outFile, $filecount
    $fileheader            >> $outFile
    $filelist              >> $outFile
    $filedata + $filebreak >> $outFile
  }
}


Concatenate all text files
gci c:\docs\* -inc *.txt -rec | concatFiles c:\temp\out.txt

#powershell console output
C:\docs\file1.txt
C:\docs\file7.txt
2 files

#file output
03-01-11 14:09:22
concat output file: c:\temp\out.txt
2 files
C:\docs\file1.txt
C:\docs\file7.txt
--------------------------------
file: C:\docs\file1.txt
file 1
...
--------------------------------
file: C:\docs\file7.txt
file 7
...
--------------------------------


Concatenate files modified on Jan 1 2011 or later
$files = "*.htm","*.css","*.js"
gci c:\docs\* -inc $files -rec -force -ea silentlycontinue |
  ?{$_.lastwritetime -gt [datetime]'01-01-2011'} | concatFiles c:\temp\out.txt

No comments:

Post a Comment