Home > Back-end >  Including result of string joining command in command line tool call powershell 5.0
Including result of string joining command in command line tool call powershell 5.0

Time:11-16

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?

CodePudding user response:

Going simpler works ok in Windows Sandbox, with an array of strings with or without extra double quotes. I printed a webpage to pdf to make a sample pdf.

$items_to_merge = (get-childitem *.pdf).name

$items_to_merge
pdftk $items_to_merge cat output test.pdf

Or with a wildcard:

pdftk *.pdf cat output test.pdf

CodePudding user response:

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"

CodePudding user response:

Let PowerShell do the quoting of the file names. By using @ instead of $ in front of the variable name, PowerShell expands the array into individual arguments (aka array splatting) which will be quoted if necessary.

$items_to_merge = (get-childitem *.pdf).name
pdftk @items_to_merge cat output test.pdf

As commenter js2010 pointed out, splatting is not even necessary. This also works:

$items_to_merge = (get-childitem *.pdf).name
pdftk $items_to_merge cat output test.pdf

Apparently PowerShell implicitly splats an array argument when passed to a native command.

Personally I still prefer explicit splatting as it consistently works with both native and PowerShell commands.

  • Related