Tomas Aschan
Tomas Aschan

Reputation: 60664

Run output of command as powershell incantation

I have a bash script that generates a program incantation (docker run ... with a bunch of arguments) and prints it to standard output. I want to run the output from powershell, with the optional possibility to tack on other arguments afterwards.

I've tried

D:\> & $(wsl ./my-bash-script.sh) some more args

but I get the error

The term 'docker run --rm -ti [<redacted>]' is not recognized as the name of cmdlet, function, script file, or operable program. Check the spelling of the name, or ifa path was included, verify that the path is correct and try again.

Apparently, & interprets the entire output as a single command, when in fact it's only the first word of the output that is a command; the rest is arguments.

Is there a way to do what I want?

Upvotes: 1

Views: 65

Answers (1)

mklement0
mklement0

Reputation: 439682

Yes, & only supports a command name or path as its first argument - you cannot include arguments.

What you need is Invoke-Expression:

Invoke-Expression "$(wsl ./my-bash-script.sh) some more args"

Note: You'd only need & inside the string if the .sh script output a command with a quoted executable path.

Also note that PowerShell will not always interpret a given command line the same way as a POSIX-like shell (such as Bash), given that it recognizes additional metacharacters at the start of arguments; notably, arguments prefixed with @ or { will not be taken as literals by PowerShell.

As an aside: While this is a legitimate use case for Invoke-Expression - assuming you trust the output from your .sh script - Invoke-Expression should generally be avoided.

Upvotes: 1

Related Questions