PowerShell: Eval Variable, String, ScriptBlock

By Xah Lee. Date: . Last updated: .

Here's how to eval a Variable, String, ScriptBlock.

The Call Operator

& $var

eval the value of a variable.

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

$xx = "dir";
& $xx
# prints dir content
& 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.

& "dir"
# prints dir content

Eval String

invoke-expression has alias iex

Invoke-Expression $var

eval the value of a variable as PowerShell expression.

$xx = "pushd; cd ~/Downloads; dir; popd";
Invoke-Expression $xx
# print dir content
Invoke-Expression string

eval string as a PowerShell Expression.

Invoke-Expression "pushd; cd ~/Downloads; dir; popd"
# print dir content

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: Profile and Script