Why can't I execute a command with arguments from a string in powershell?

In windows powershell, I try to save the move command in a line and then execute it. Can someone tell me why this is not working?

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 to overcome this limitation?

+5
source share
3 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.

Instead of a string, you can use a script block:

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

Or you can use Invoke-Expression:

Invoke-Expression $str

or

iex $str

&, Invoke-Expression , - , .

+10

, , , V2 . , , - , :

$cmd = 'mv'
$params = @{Path = 'log.txt'; Destination = 'log.bak'}
&$cmd @params

V2, splatting. , - .

. , " ", , :

$cmd = "cpi"
$params = ('log.txt', 'log.bak')
&$cmd @params

OP, , .

+5

:

, , . $program $argString & $program $argString , $argString . . & , $argString .

[string]$argString $argString += "-aaa `"b b b`"" [string[]]$argArray $argArray += @('-aaa', 'b b b'), .

$process = [Diagnostics.Process]::Start( $program, $argString ). , .

Or you can put everything in a string and use Invoke-Expression "$program $argString"that will parse the entire string as a command and execute it correctly.

As Keith mentioned , splatting is another good option in PowerShell 2.

+2
source

All Articles