What does invoke-expression do in PowerShell?

Runs commands or expressions on the local computer.

SYNTAX

Invoke-Expression [-Command] <String> [<CommonParameters>]

DESCRIPTION

The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line is returned (echoed) unchanged.

Expressions are evaluated and run in the current scope. For more information, see about_Scopes.

[!CAUTION] Take reasonable precautions when using the Invoke-Expression cmdlet in scripts. When using Invoke-Expression to run a command that the user enters, verify that the command is safe to run before running it. In general, it is best to design your script with predefined input options, rather than allowing freeform input.

EXAMPLES

Example 1: Evaluate an expression

$Command = "Get-Process" $Command

Invoke-Expression $Command

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 296 4 1572 1956 20 0.53 1348 AdtAgent 270 6 1328 800 34 0.06 2396 alg 67 2 620 484 20 0.22 716 ati2evxx 1060 15 12904 11840 74 11.48 892 CcmExec 1400 33 25280 37544 223 38.44 2564 communicator ...

This example demonstrates the use of Invoke-Expression to evaluate an expression. Without Invoke-Expression, the expression is printed, but not evaluated.

The first command assigns a value of Get-Process (a string) to the $Command variable.

The second command shows the effect of typing the variable name at the command line. PowerShell echoes the string.

The third command uses Invoke-Expression to evaluate the string.

Example 2: Run a script on the local computer

Invoke-Expression -Command "C:\ps-test\testscript.ps1" "C:\ps-test\testscript.ps1" | Invoke-Expression

These commands use Invoke-Expression to run a script, TestScript.ps1, on the local computer. The two commands are equivalent. The first uses the Command parameter to specify the command to run. The second uses a pipeline operator (|) to send the command string to Invoke-Expression.

Example 3: Run a command in a variable

$Command = 'Get-Process | where {$_.cpu -gt 1000}' Invoke-Expression $Command

This example runs a command string that is saved in the $Command variable.

The command string is enclosed in single quotation marks because it includes a variable, $_, which represents the current object. If it were enclosed in double quotation marks, the $_ variable would be replaced by its value before it was saved in the $Command variable.

Example 4: Get and run a cmdlet Help example

$Cmdlet_name = "Get-ComputerInfo" $Example_number = 1 $Example_code = (Get-Help $Cmdlet_name).examples.example[($Example_number-1)].code Invoke-Expression $Example_code

This command retrieves and runs the first example in the Get-EventLog cmdlet Help topic.

To run an example of a different cmdlet, change the value of the $Cmdlet_name variable to the name of the cmdlet. And, change the $Example_number variable to the example number you want to run. The command fails if the example number is not valid.

[!NOTE] If the example code from the help file has output in the example, PowerShell attempts to run the output along with the code and an error will be thrown.

PARAMETERS

-Command

Specifies the command or expression to run. Type the command or expression or enter a variable that contains the command or expression. The Command parameter is required.

Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False

CommonParameters

This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.

INPUTS

System.String or PSObject

You can pipe an object that represents the command to Invoke-Expression. Use the $Input automatic variable to represent the input objects in the command.

OUTPUTS

PSObject

Returns the output that is generated by the invoked command (the value of the Command parameter).

NOTES

In most cases, you invoke expressions using PowerShell's call operator and achieve the same results. The call operator is a safer method. For more information, see about_Operators.

Invoke-Command

about_Scopes


Page 2

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Invoke-Expression is a language feature that allows for capturing the output of a command line application for parsing by your powershell script. If you are not careful, though, you could be plagued with messages like these:

Invoke-Expression : You must provide a value expression on the right-hand side of the '-' operator.At C:\Users\Administrator\temp\someScript.ps1:3 char:29+ $results = Invoke-Expression <<<<  $Action    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException

    + FullyQualifiedErrorId : ExpectedValueExpression,Microsoft.PowerShell.Commands.InvokeExpressionCommand

For the last few months I've been using Invoke-Expression something like this:

$Action = "Certutil.exe –addstore –enterprise root $Certificate" $result = Invoke-Expression $Action

This works fine if the EXE you are referencing is in one of the locations defined by the windows PATH Variable

If you attempt to run something like this, though, you will run into problems:

$Action = "c:\program files (x86)\nmap\nmap.exe -p 123 -sU -P0 time.windows.com" $results = Invoke-Expression $Action

This code block returns the following error:

The term 'c:\program' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:11+ c:\program <<<<  files (x86)\nmap\nmap.exe -p 123 -sU -P0 time.windows.com -oN c:\test.log --append-output

    + CategoryInfo          : ObjectNotFound: (c:\program:String) [], CommandNotFoundException


    + FullyQualifiedErrorId : CommandNotFoundException

On the surface it seems fairly obvious what the next step should be: enclose the path to the exe in quotation marks taking care to escape them using the PowerShell back tick character ( ` ):

$Action = "`"c:\program files (x86)\nmap\nmap.exe`" -p 123 -sU -P0 time.windows.com" $results = Invoke-Expression $Action

This puts us closer to our objective, but it still returns an error:

Invoke-Expression : You must provide a value expression on the right-hand side of the '-' operator.At C:\Users\Administrator\someScript.ps1:3 char:29+ $results = Invoke-Expression <<<<  $Action    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException

    + FullyQualifiedErrorId : ExpectedValueExpression,Microsoft.PowerShell.Commands.InvokeExpressionCommand

This error baffled me for about an hour before I found out what needed to be done next: prefix the double-quoted path to the EXE with an ampersand like this:

$Action = "&`"c:\program files (x86)\nmap\nmap.exe`" -p 123 -sU -P0 time.windows.com" $results = Invoke-Expression $Action

Without the ampersand ( & )  character, Powershell parses the expression as a string rather than as a command. In this case we have to be explicit and tell Powershell that there is a command in there that we want to run. While it makes for some gnarly syntax, it does the trick.

Addendum (14-July-2012): I recently ran into a problem that requires a slight alteration to the solution provided above.

Problem

If you have an executable that requires a quoted or double quoted parameter you may be surprised to note that this seemingly obvious syntax does not work:

iex "&`"C:\Program Files\Vendor\program.exe`" -i -pkg=`"Super Upgrade`" -usr=User -pwd=password2"

The above-syntax simply escapes the double quotes around the parameter so they should be passed along to the EXE. Unfortunately you get this error:

What does invoke-expression do in PowerShell?


Invoke-Expression : The string starting:
At line:1 char:62
+ &"C:\Program Files\Vendor\program.exe" -i -pkg="Super Upgrade <<<< " -usr=User -pwd=password2
is missing the terminator: ".At line:1 char:4+ iex <<<<  "&`"C:\Program Files\Vendor\program.exe`" -i -pkg=`"Super Upgrade`" -usr=User -pwd=password2"    + CategoryInfo          : ParserError: ( -usr=User -pwd=password2:String) [Invoke-Expression], IncompleteParseException

    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString,Microsoft.PowerShell.Commands.InvokeExpressionCommand

Solution

The Baffling solution in my case was to triple-escape the double-quoted parameter. What makes this so confusing is that I only have to triple escape the closing quote:

iex "&`"C:\Program Files\Vendor\program.exe`" -i -pkg=`"Super Upgrade```" -usr=User -pwd=password2"

YMMV