Search code examples
powershellpdftk

Including result of string joining command in command line tool call powershell 5.0


I would like to include the result of a string concatenation command as part of a call using the pdftk command line tool. Here's what I tried:

$items_to_merge = '"' + $($(get-childitem *.pdf).name -join '" "') + '"'

echo $items_to_merge
pdftk $items_to_merge cat output test.pdf

The individual pdf file names themselves include spaces, so that's why I'm wrapping every file name with double quotes.

However it turns out that when I run this command I get pdftk errors as follows:

Error: Unable to find file

I'm a bit surprised because enumerating the files by hand and wrapping with double quotes has always worked. Why does it fail when I do it programmatically?


Solution

  • In this kind of situation invoke-expression is your friend:

    $items_to_merge = '"' + $($(get-childitem *.pdf).name -join '" "') + '"'
    echo $items_to_merge
    invoke-expression "pdftk $items_to_merge cat output test.pdf"