1

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.

1 Answer 1

2

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.

1
  • I had tried without the quotes, and it did not work, I guess I was missing the & $String. Jun 15, 2013 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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