Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I execute a commandlet with arguments from a string in powershell?

Tags:

powershell

In windows powershell, I am trying to store a move command in a string and then execute it. Can someone tell me why this doesn't work?

PS C:\Temp\> dir
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Temp

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         8/14/2009   8:05 PM       2596 sa.csproj
-a---         8/15/2009  10:42 AM          0 test.ps1


PS C:\Temp> $str = "mv sa.csproj sb.csproj"
PS C:\Temp> &$str
The term 'mv sa.csproj sb.csproj' is not recognized as a cmdlet, function, operable program, or script file. Verify the
 term and try again.
At line:1 char:2
+ &$ <<<< str
PS C:\Temp>

I get this error when storing any command with arguments. How do I overcome this limitation?

like image 277
George Mauer Avatar asked Aug 15 '09 18:08

George Mauer


1 Answers

From the help (about_Operators):

&  Call operator
  Description: Runs a command, script, or script block. Because the call
  operator does not parse, it cannot interpret command parameters.

You can use a script block instead of a string:

$s = { mv sa.csproj sb.csproj }
& $s

Or you can use Invoke-Expression:

Invoke-Expression $str

or

iex $str

In contrast to &, Invoke-Expression does parse the string contents, so you can put anything in there, not just a single command.

like image 84
Joey Avatar answered Sep 24 '22 19:09

Joey