Executing a string as PowerShell command
The following example creates a string whose content is write-output (3*14)
and then passes it to invoke-expression
. Thus, when run, the example prints 42
:
$num_1 = 3
$num_2 = 14
$operation = '*'
invoke-expression "write-output ($num_1 $operation $num_2)"
Executing the commands in a file
invoke-expression
can also be used to execute the commands that are stored in a file (that is: a script).
The following script uses
split-path $myInvocation.myCommand.path
to determine the directory where it is located and assigns the value to the
variable $dir
. It then uses
$dir
to execute a powershell that is located in
$dir
and is named
commands.ps1
. Note, that the
file extension .ps1
is not required when using the
-command
parameter:
$dir = split-path $myInvocation.myCommand.path
invoke-expression -command "$dir/commands.ps1"
I am not sure if this construct allows to do something that is not possible just using the
call operator (&
).
Combining with get-content
Here's a file with a simple expression:
$THE_NUMBER = 7 * $someNumber
The content of this file is read using
get-content
and then piped into
invoke-expression
:
$someNumber = 6
get-content an-expression.txt | invoke-expression
write-output "The number is: $THE_NUMBER"
When executed, it prints
The number is: 42
Piping the contents of a file into invoke-expression
An expression that is stored in a file can be read with
get-content
and then
piped into
invoke-expression
:
$dict = get-content -raw expression.txt | invoke-expression
"num = $($dict.num)"
"txt = $($dict.txt)"
The file with the expression:
@{
num = 42
txt = 'hello world'
}
Passing a multi-line string
In order to evaluate an expression that is stored in a multi-line string, the ends of the continued lines need to be escaped twice:
set-strictMode -version latest
function func($p_1, $p_2, $p_3) {
write-host "p_1 = $p_1"
write-host "p_2 = $p_2"
write-host "p_3 = $p_3"
}
invoke-expression "func ``
-p_2 2 ``
-p_1 one ``
-p_3 III
"