PowerShell: Eval Variable, String, ScriptBlock
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
(aliassajb
)-
Start a PowerShell background job.
PowerShell: Profile and Script
- PowerShell: Open File by Default App
- PowerShell: Launch App, Start Process
- PowerShell: Load a Script
- PowerShell: Eval Variable, String, ScriptBlock
- PowerShell: Profile (init file)
- PowerShell: Manage PowerShell Profiles
- PowerShell: Create a Script
- PowerShell: File Name Extension
- PowerShell: Get Current Script Path