0

How can I run a command + arguments inside a variable using powershell from cmd?

This is what works fine:

powershell -c " $test='dir'; &($test) "

But when I supply an argument to the command, for example:

dir /a -> powershell -c " $test='dir /a'; &($test) "

I get this error:

&: The term 'dir /a' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
In line:1 char:19
+  $test='dir /a'; &($test)
+                   ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (dir /a:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

This is what I tried but did not work:

powershell -c " $test='dir /a'; &($test) "
powershell -c " $test='dir /a'; Invoke-Expression '&$test' "
powershell -c " $test='dir /a'; Invoke-Expression """&($test)""" "
powershell -c " $test='dir /a'; Invoke-Expression '&($test)' "
powershell -c " $test='dir /a'; Invoke-Expression &($test) "

How can I execute the content of $test, without pipeing to cmd?

  • `$cmd = 'dir';$arg = '/a'; & $cmd $arg` – Mathias R. Jessen Jun 27 '23 at 13:05
  • @MathiasR.Jessen it gives me the following error: "Get-ChildItem : Cannot find path 'C:\a' because it does not exist." seems like it does not treat the '/a' in the intended way –  Jun 27 '23 at 13:09
  • 1
    If you want to run the command in `cmd.exe`, that _that_ is the command name: `$cmd = 'cmd.exe';$arg = '/c','dir','/a'; & $cmd @arg` – Mathias R. Jessen Jun 27 '23 at 13:10
  • Except for the `cmd.exe` angle (mistakenly trying to invoke a command that is internal to `cmd.exe` directly from PowerShell), your question is a duplicate of [this one](https://stackoverflow.com/q/38064512/45375). – mklement0 Jun 27 '23 at 13:19

1 Answers1

1

The error says it all - 'dir /a' is not the name of a visible PowerShell command!

Split the command name and arguments into separate parts and it'll work:

powershell -c "$cmd = 'dir'; $arg = '/a'; &$cmd $arg"

Note that PowerShell is not cmd.exe - if you want to run a one-off command in cmd.exe, you'll need to invoke cmd.exe, followed by the /c command line switch and then the command expression you want it to execute:

powershell -c "$cmd = 'cmd.exe'; $arg = '/c','dir','/a'; &$cmd @arg"
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • big thanks! but does exist another way to execute the same thing, without spawning another cmd.exe process? because it actually is cmd.exe -> powershell -> cmd.exe –  Jun 27 '23 at 13:19
  • No, you can't launch cmd.exe without launching cmd.exe :) – Mathias R. Jessen Jun 27 '23 at 13:20