PowerShell: Eval {Variable, String, Script, Block}

By Xah Lee. Date: . Last updated: .

Here's how to eval a Variable, String, Script, Block.

The Call Operator

& $var
eval the value of a variable.

useful when you have a command in string stored as variable.

$xx = "dir";
& $xx
& str
eval a simple command in str.

Note: str should be one of:

  • A command name
  • A function name
  • File path of a script, executable, app.

Warning: it cannot eval expression. e.g. & "1+1" is error.

To eval arbitrary string or expression, use Invoke-Expression.

Eval String, Run a Script

invoke-expression has alias iex

Invoke-Expression $var
eval the value of a variable as PowerShell expression.
$xx = "pushd; cd; dir; popd";
Invoke-Expression $xx
Invoke-Expression string
eval string as a PowerShell Expression.
Invoke-Expression "pushd; cd; dir; popd"
Invoke-Expression scriptPath
run a PowerShell script.
Invoke-Expression "~/powershell/xx.ps1"

Eval a Script Block

invoke-command has alias icm

Invoke-Command -ScriptBlock {code}
run a script block.
Invoke-Command {pushd; cd; dir; popd}

Start Background Process

Start-Job (alias sajb)
Start a PowerShell background job.

PowerShell: Launch, Open, Eval

PowerShell: Profile and Script