0

Im looking for a powershell script which prompts user to select multiple files. After selection is confirmed, I want to combine all selected files into one file. Here is what I could manage so far

Function Get-FileName($initialDirectory)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = "TXT (*.txt;*.log)| *.txt;*.log"
    $openFileDialog.MultiSelect = $true
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.FileNames
}
$inputfiles = Get-FileName "C:\temp"
$inputfiles
cmd /c copy /b $inputfiles out.txt

The files are usually big text/log files with millions of lines in each file and so far copy via cmd is the fastest way I know of to combine big files.
The current script copies only first file in $inputfiles . How can I get this to work to combine all files?

n00b321
  • 1
  • 1
  • Also read this related post, since your files seem to be huge: https://stackoverflow.com/questions/1783554/fast-and-simple-binary-concatenate-files-in-powershell – David Brabant Sep 15 '17 at 09:14
  • I used a solution in a comment from that question only to merge my files via cmd – n00b321 Sep 15 '17 at 09:21

1 Answers1

0

This is an simple example how you can do it. I have replaced your openfiledialog with out-gridview

#Get files and prompt them in Grid-View
$Files = Get-ChildItem -Path 'C:\temp\SC Test' -Recurse -Include *.txt, *.log | Select-Object -Property Name, DirectoryName, FullName | Out-GridView -PassThru -Title "select files to merge"
#path for the new file with the content
$MergedFilePath = "C:\temp\merged.txt"

#Loop selected files from gridview
Foreach($File in $Files){
    #Get text from file and write the text to the new file
    Get-Content -Path $File.FullName | Out-File -FilePath $MergedFilePath -Encoding utf8 -Append
}
guiwhatsthat
  • 2,349
  • 1
  • 12
  • 24
  • I just tested your script on 7 files. it took +3 minutes to complete. TotalMinutes : 3.149990845 TotalSeconds : 188.9994507 using cmd it takes like TotalMinutes : 0.00320825666666667 TotalSeconds : 0.1924954 thats why I went with my approach. I just cant seem to figure out how to merge file names in a array/variable via cmd – n00b321 Sep 15 '17 at 09:16
  • This merge part should be faster. Get-Content -Path $Files.FullName | Add-Content -Path $MergedFilePath -Encoding utf8 in this case you can remove the loop and note that the file $MergedFilePath must exist – guiwhatsthat Sep 15 '17 at 10:39