tags:

views:

190

answers:

2

Can someone help me explain what is happening here? Sorry if this is a basic question, I simplified it from a pipeline expression I'm 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, operable program, or script file. Verify the term and try again.

At line:1 char:2 + & <<<< "dir $foo"*

dir pwd #Error

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

At line:1 char:4 + dir <<<< pwd*

I would expect all four of these to yield the same results

+4  A: 

Expressions in quotes are interpreted as a single argument. In the third command, the shell is interpreting it as a request for the command "dir C:\" with no arguments, rather than a request for the command "dir" with an argument of "C:\".

mobrule
+5  A: 

If you want to "execute" a string containing arbitrary script use the Invoke-Expression cmdlet e.g.:

Invoke-Expression "dir $foo"

Keith Hill
Keith I'm reading the section from your ebook that talks about the different parsing modes (Item 7 Page 31) it is helpful; but I haven't quite got it sorted out yet. I thought the but it appears there are some subtle differences do you know where I can find out more? I tried the msdn docs; but that didn't add a whole lot.
JasonHorner
Keith Hill