Issue about command execution in powershell

Can someone help me explain what's going on here? Sorry if this is the main question, I have simplified it from a pipeline expression I am trying to write:

$foo = pwd
$cmd = "dir"

& $cmd $foo #Works

dir $foo  #Works

& "dir $foo" #Error

      

* The term "dir C: \" is not recognized as a cmdlet, function, operating program, or script file. Please check this term and try again.

On line: 1 char: 2 + and <"dir $ foo" *

dir pwd #Error

      

* Get-ChildItem: Cannot find path "C: \ pwd" because it does not exist.

On line: 1 char: 4 + dir <PWD *

I expect all four of them to give the same results

+2


source to share


2 answers


Quoted expressions are interpreted as a single argument. In the third command, the shell interprets it as a command prompt dir C:\

with no arguments, rather than a command prompt dir

with an argument C:\

.



+5


source


If you want to "execute" a line containing an arbitrary script, use the Invoke-Expression cmdlet, for example:



Invoke-Expression "dir $ foo"

+5


source







All Articles