Building code at runtime
How to use Invoke-Expression
Invoke-Expression is a way to execute an arbitrary string as a piece of code
example:
Invoke-Expression '$a = 10 + 20 ; $a'
Output:
30
if you use this expression
Invoke-Expression '$a++'
$a
output:
31
ExecutionContext Variable
$ExecutionContext is the way to get at variable facilities provided by the powershell engine
example:
$ExecutionContext
output:
you can get output about Host,invokeprovider,sessionstate and invokecommand
$ExecutionContext.InvokeCommand | Get-Member
output:
How to use ExpandString
expandstring is method that lets you perform the same kind of variable interpolation that the powershell runtime does in scripts
example:
$test = 100
$s = 'this is $test'
you got : this is $test
if you want to get value of variable you can use this command
$ExecutionContext.InvokeCommand.ExpandString($s)
output:
this is 100
InvokeScript
invokescript is method . this method does the same thing that the invoke-expression
example:
$ExecutionContext.InvokeCommand.InvokeScript("100+200")
output:
300
[With great power comes great responsibility]