Prof. Powershell

Express Yourself with the Invoke-Expression Cmdlet

The Invoke-Expression cmdlet: Turn it on and you can do almost anything.

Windows PowerShell is not too difficult to operate. You type a command and something happens. Usually you are running PowerShell cmdlets, scripts, functions or even non-PowerShell commands like ipconfig.

But maybe you'd like to define a command, and run it later. Or perhaps construct a command on the fly. To run these commands you'll need to turn to the Invoke-Expression cmdlet. Here's a very simple example:

PS C:\> $c="arp -a"
PS C:\> invoke-expression $c

Interface: --- 0x20
  Internet Address Physical Address  Type   ff-ff-ff-ff-ff-ff static       01-00-5e-00-00-16 static      01-00-5e-00-00-fc static       01-00-5e-00-01-3c static  ff-ff-ff-ff-ff-ff static

I defined a variable, $c, that contains a command string. Whenever I want to run it, I call Invoke-Expression. You can also use the alias iex. But be careful. Suppose you want to take this expression and save it as a string so you can use Invoke-Expression:

get-service | where {$_.status -eq "Running"}

You'll need to enclose this is single quotes:

PS C:\> $c=' get-service | where {$_.status -eq "Running"}'
PS C:\> iex $c | measure-object

Count : 68
Average :
Sum :
Maximum :
Minimum :
Property :

You can also construct an expression, and include variables:

PS C:\> $c="get-wmiobject"
PS C:\>$c+=' -class $class'

These two statements combine to create the expression get-wmiobject -class $class. This is intentionally a very simple example to make my point. Let's continue:

PS C:\> $class="win32_bios"
PS C:\> iex $c

Manufacturer : LENOVO
Name : Rev 1.0
SerialNumber :
Version : LENOVO - 6040000

I can reset $class, and re-invoke $c anytime I want.

PS C:\> $class="win32_computersystem"
PS C:\> iex $c

Manufacturer : LENOVO
Model : S10-3
Name : QUARK
PrimaryOwnerName : Jeff
TotalPhysicalMemory : 2136391680

Finally, you can also pipe one or more expressions to Invoke-Expression, and the cmdlet will execute each one:

PS C:\> "arp -a","nbtstat -n" | iex | out-file c:\work\stats.txt

With this expression I executed two commands and saved the results to a text file.

Most of the time, you know what command you want to run and simply do it. But when you might need to construct a command on the fly or execute something arbitrarily, take a look at Invoke-Expression.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular