Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

In response to this question, the original requester wanted to know

In PowerShell, is there a way, after typing a long or complicated command, to commit that command into the history buffer, but not execute it?

My solution however was purely for fun, but I wondered how / why it worked on the back end.

Answer

$VariableName = "Windows Command"

Then, to execute:

Invoke-Expression "$VariableName"

An example with Ping:

enter image description here

I was also able to use PowerShell expressions in the exact same way:

PS H:> $Outlooks = "Get-Process -Name Outlook -Verbose | fl StartTime, Threads"
PS H:> Invoke-Expression "$Outlooks"

My Theory

Essentially, I believe what is happening is that we are creating a string for the first variable (Exactly what it looks like, straight forward), and then when we invoke our variable inside " " it forces the interpreter to expand the variable, causing it to call the right command.

Is my understanding of how this works accurate? References preferred.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Yep, that seems to be exactly what is happening (BTW you don't even need quotes around the command string while invoking).

As per the help description of the cmdlet (obtained via get-help Invoke-Expression -full):

iex [-Command] <String> [<CommonParameters>]
Invoke-Expression [-Command] <String> [<CommonParameters>]

The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.

An expression is a statement that can be evaluated and produces a result, such as a Windows PowerShell command.

If the command stored in the string variable is not too complex you can also use the call operator (&) as follows:

& $string

Further details courtesy this page:

If the result of the expression is an empty array, invoke-expression will output $null

Invoke-Expression can be used to perform string expansion but if the string is supplied by an end-user you need to ensure that it does not contain malicious code/expressions.

share|improve this answer
    
I had tried without the quotes, and it did not work, I guess I was missing the & $String. –  AthomSfere Jun 15 '13 at 13:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.