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:
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”:
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:
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.