I want to merge all .docx files within a folder with a .bat file (no Powershell, as I'd need to make sure the target computers are all set to allow powershell scripts). It would be great if the output file was named after the parent folder name.
There is a command line utility for merging docx files here:
https://github.com/jamessantiago/DocxMerge
It needs the following syntax: docxmerge.exe -i $input_files -o $output_file_name
Simple version (should work once/if docxmerge fixes the sorting bug = unlikely)
@echo off & setlocal enabledelayedexpansion
cd %1
set files=
for %%i in (*.docx) do set files=!files! "%%i"
set name=
for %%i in (.) do set name=%%~nxi
DocxMerge.exe -i %files% -o "%name%.docx" -f
=> works 90%, but: the output.docx contains the documents in the wrong order:
%files% if echoed gives me the filenames in the correct, alphabetical order. For some reason though, after docxmerge runs it gives me the following order:
Example for 10 page document
Page 1
Page 10
Page 9
...
Page 2
========
I need to reorder from the current alphabetical list as follows:
- file 1
- rest of the files in reverse order (i.e. 10, 9, ..., 2)
============================================================
Workaround version:
@echo off & setlocal enabledelayedexpansion
set name=
for %%i in (.) do set name=%%~nxi
del /f %name%.docx
set files=
set firstFile=
for %%i in (*.docx) do (
if [!firstFile!]==[] (
set firstFile="%%i"
) else (
set files="%%i" !files!
)
)
set files=%firstFile% %files%
DocxMerge.exe -i %files% -o "%name%.docx" -f
dir
command:dir /b /o-n *.docx
. Or else useset "row=%%x !row!"
instead. The encoding issue might be fixed by setting a different codepage:chcp 65001