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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With