August 31, 2015

PowerShell - The Call Operator "&"

The call operator "&" is a powerful feature in PowerShell. If you place this operator in front of a string, or a string variable, the string will be interpreted as a command and executed just as if you had input it directly into the console. Let put a command (Dir) in a variable and if you output the contents of the variable, only string will be output:

$myCommand = "Dir"
$
myCommand
Dir

If you type the call operator "&" in front of it, the command will be executed:
& $myCommand

The call operator will not run an entire instruction line but only single command. If you
had also specified arguments for the command, you will get an error:
$myCommand = "Dir C:\"
& $
myCommand

Event if you put an space in command name, you will get same error. For example:
$myCommand = "Dir "
& $
myCommand
 Also generates the error.

Another way to assign a command to a variable is using Get-Command cmdlet, and then use the same call operator to invoke this command.
$myCommand = Get-Command Dir
& $
myCommand

But keep in mind that & $myCommand calls the actual command in $myCommand. You may specify any arguments after it, but you can't put the arguments directly in $command because the call operator always executes only one single command without arguments. So following call will work:
$myCommand = "Dir"
& $
myCommand "c:\"

No comments:

Post a Comment