In what scenario was Invoke-Expression designed to be used?

To quote from a PowerShell team blog post titled Invoke-Expression considered harmful (emphasis added):

The bottom line: Invoke-Expression is a powerful and useful command for some scenarios such as creating new scripts at runtime, but in general, if you find yourself using Invoke-Expression, you should ask yourself, or maybe a respected colleague if there is a better way.

EBGreen notes:

Or to phrase it another way, It [Invoke-Expression] is ok to use as long as a user is never involved in any part of generating the string that will be invoked. But even then, not using it will enforce better habits than using it would.

In short:

  • As a matter of habit, always consider a different (usually more robust and secure) solution first.

  • If you do find that Invoke-Expression is your only choice, carefully consider the security implications: if a string from an (untrusted) outside source (e.g., user input) is passed directly to Invoke-Expression, arbitrary commands may be executed.

    • Therefore: Only use Invoke-Expression if you fully control or implicitly trust the input.

Note: As of Windows PowerShell v5.1 / PowerShell Core v6.1.0, the official Invoke-Expression help topic doesn’t provide such guidance; this GitHub issue suggests rectifying that.


Rare examples of justified (safe) use of Invoke-Expression:

Leave a Comment