Powershell

Invoke-Expression: The Universal PowerShell Executor Cmdlet

The cmdlet “Invoke-Expression” in PowerShell executes the expressions on the local computer. This cmdlet has the capability to run the scripts or strings as a command and gets the results of the command in PowerShell. In other words, it accepts the string to be executed as a code. When the string is submitted to the command line without this cmdlet, the result will be unchanged.

The following blog will consider several prospects to explain the “Invoke-Expression” cmdlet.

How to Use the “Invoke-Expression” Cmdlet in PowerShell?

As stated earlier, the “Invoke-Expression” cmdlet helps to run or evaluate a string or script as a command. Further usage is elaborated on in the given examples below.

Example 1: Utilize the “Invoke-Expression” Cmdlet to Evaluate a Command

This example will evaluate an expression using the “Invoke-Expression” cmdlet:

$Cmdlet = "Get-Service"

Invoke-Expression $Cmdlet

According to the above code:

  • First, initialize a variable “$cmdlet” and assign the “Get-Service” cmdlet to it.
  • After that, use the “Invoke-Expression” cmdlet to invoke the “$cmdlet” variable:

Example 2: Utilize the Cmdlet “Invoke-Expression” to Run a Command in a Variable

This example will run a command in a variable using the cmdlet “Invoke-Expression”:

$cmdlet = 'Get-Process | Select-Object -ExpandProperty Name -Last 5'

Invoke-Expression $Cmdlet

According to the above code:

  • First, initialize the variable “$cmdlet” and assign the command to it.
  • After that, utilize the cmdlet “Invoke-Expression” to call the command assigned variable “$cmdlet”:

Example 3: Utilize the Cmdlet “Invoke-Expression” to Execute the Script in PowerShell Console

Now, execute the below command:

Invoke-Expression "C:\New\TestScript.ps1"

To run the script in the PowerShell console, first, add the “Invoke-Expression” cmdlet and then specify the script path within double inverted quotes:

It can be observed that the script in the PowerShell console was successfully invoked using the “Invoke-Expression” cmdlet.

Conclusion

The “Invoke-Expression” cmdlet is known for running or evaluating a string as a command in PowerShell. First, it stores the script or string in a variable, and then it invokes the string-assigned variable. This blog has explained the “Invoke-Expression” cmdlet with multiple examples.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.