0

Let's say I want to get a specific dir contents:

$cmd = "dir"
$args = ".yarn*"
$output = "$cmd $args"

echo $output

My output contains 2 string literals:

dir .yarn*

Expected (as a command on 1 line, opposed to a "string" on separate lines):

dir *yarn
dylanh724
  • 948
  • 1
  • 12
  • 29
  • WHy would you like to put the command in a variable? – Olaf Aug 26 '22 at 08:35
  • 2
    `$output = $cmd $args` is not a valid statement, it causes an error. Please create a valid [mcve]. You probably want to do something like: `Invoke-Expression "$cmd $args"`. Take reasonable precautions when using the Invoke-Expression cmdlet in scripts. When using [Invoke-Express](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-expression#description)ion to run a command that the user enters, verify that the command is safe to run before running it. In general, it is best to design your script with predefined input options, rather than allowing freeform input. – iRon Aug 26 '22 at 08:38
  • "Why would you like to put the command in a variable?" >> Dynamic command building - it's not ready yet until $output. Example: `git commit` you don't know yet if it will append a description, or just a message. I could surely have bloaty if/then statements that print the entire command; but not preferable. Imagine a giant command I want to build. – dylanh724 Aug 26 '22 at 08:38

1 Answers1

-1

@iRon 's comment with a suggested answer was correct:

Invoke-Expression($output) is the answer!

dylanh724
  • 948
  • 1
  • 12
  • 29