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

By Xah Lee. Date: .

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

The Call Operator

& $var
eval the value of a variable.
$xx = "dir";
& $xx
& str (call operator)
eval a simple command in str.

Note: str should be one of:

  • a command name
  • a function name
  • a script file path

For example, & "1+1" is error.

To eval a string that is not just a command name, or contains space, or arbitrary 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 "~/web/xahlee_info/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

PowerShell

Practical How-To

list files

list dirs

on dir

on file

Windows config

zip tar

misc


PowerShell in Depth

Programing PowerShell

Value Types

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples