To run a command stored in a variable in PowerShell, use the call operator, &. It invokes a command name, executable path or script block while allowing arguments to be supplied separately.
Run a command stored in a variable
Use the & operator in PowerShell to execute the content of a variable. See the example below:
$CommandInAVariable = 'Write-Host' & $CommandInAVariable -ForegroundColor green 'Hello World!'
The variable contains only the command name. The remaining tokens are normal arguments, so PowerShell binds the color and message parameters correctly.
Run an executable path with spaces
$program = 'C:\Program Files\Example\tool.exe'
& $program '--version'
Avoid unnecessary Invoke-Expression
Prefer the call operator when command and arguments are separated. Untrusted text passed to Invoke-Expression can execute injected code. See Microsoft's PowerShell operators reference and the PowerShell abbreviation table.

Comments