Automating the world one-liner at a time…
The PowerShell team frequently gets questions that start out “how do I get the quoting right for…” and the answer turns out to usually be – there is a simpler way – don’t use Invoke-Expression.
The problem arises when trying to run some command external to PowerShell. Some common reasons people try Invoke-Expression:
If you’re just running some command external to PowerShell (exe, cmd, etc.) and you’re using Invoke-Expression, you are just making things more difficult than you need to.
So what’s wrong with Invoke-Expression then?
If Invoke-Expression isn’t the right way – then what is?
If you’re running some command and the command path has spaces in it, then you need the command invocation operator ‘&’ (see help about_operators, look for “call operator”).
If your command runs, but your arguments are wrong, then there is a good chance you are getting the quotes wrong. Invoke-Expression doesn’t help at all in this case, it just makes the problem more complicated.
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.
Jason Shirk Windows PowerShell Team
I blogged about this once too! 0ptikghost.blogspot.com/.../executing-native-commands-in-powershell.html
Still it is not clear to me why invoke-expression is pron to code injections when compared to using invocation operator '&'. Any example is appreciated.
When the quoting on command arguments starts to get complicated, I usually just put the darned thing into a here-string and run that. Double qoted if I need to do substitution, single if not. It saves a lot of futzing around with escaping and quotes stacked two and sometimes 3 deep around arguments.
I don't get it.
People use it even when there's obviously no need to. This is what happens when you add do-not-use features to a programming language.