Invoke Expression - PowerShell


Overview

Invoke-Expression evaluates and executes a specified string as a PowerShell expression. It allows you to execute complex commands or scripts dynamically, making it versatile for automating tasks.

Syntax

Invoke-Expression [-Command] <string> [-Session] <PSSession> [-AsJob]

Parameters

  • Command: Specifies the string to be evaluated and executed as a PowerShell expression.
  • Session: Optionally specifies a PowerShell session in which to execute the expression.
  • AsJob: Runs the expression as a background job.

Options/Flags

  • -ErrorAction: Specifies the action to be taken when the expression encounters an error. Default: Continue
  • -PassThru: Returns the result of the expression to the pipeline. Default: False
  • -Variable: Defines a variable in the current scope before executing the expression.

Examples

Simple Expression:

Invoke-Expression 'Get-Date'

Complex Expression:

$path = 'C:\temp'
Invoke-Expression "Set-ACL -Path $path -User everyone -Access rights FullControl"

Custom Variable:

$myVariable = 'My Value'
Invoke-Expression -Variable myVariable 'Write-Host $myVariable'

Common Issues

  • Invalid Expression: Ensure the provided string is a valid PowerShell expression.
  • Insufficient Permissions: Make sure you have sufficient permissions to execute the specified expression or commands within it.

Integration

Chaining Commands:

Get-Service | Invoke-Expression 'Stop-Service -Service $_' | Invoke-Expression 'Get-Service -Service $_'

Creating Scripts:

$scriptText = 'Get-Process | Sort-Object CPU -Descending'
Invoke-Expression -Command $scriptText > C:\scripts\top_processes.ps1
  • Get-Command: Retrieves commands from the PowerShell command dictionary.
  • Write-Host: Outputs a string to the console.
  • Set-Variable: Creates or modifies a variable in the current scope.