4

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?

For example, you start typing a git commit, within posh-git:directory:

git commit -m "Added the library 'ASDF' and did some initial integration into the project" [pause]

And right when you get that typed, I'm thinking... Uh, I need to do something first, like add an additional file to commit do something else first, or create a directory or something (contrived situation, I realize Powershell will auto-create it and I realize git can "amend the commit".) So I'd like to save that commit message into a history buffer, but without running it, to be recalled later after I say, stage additional files or do something just before.

According to this article, Windows PowerShell Shortcut Keys: http://technet.microsoft.com/en-us/library/ee176868.aspx , there doesn't appear to be a keystroke to do this.

ESC key (and Ctrl+C) will cancel the command, and clear it out... What I need is to save to history, to be run later, thus preserving my typing. Is there a keystroke for this?

10

Well you can always put a comment tag before the command like this:

#Get-ChildItem

And when you are ready to execute, arrow up to the command hit Home then Del, then Enter to execute.

  • thats pretty clever. thanks for the suggestion! – enorl76 Jun 11 '13 at 15:29
  • Yep. Been using this trick for forever. I also comment my oneliners this way, because I might actually reread the history years from now (bash). – bgStack15 Jan 15 '15 at 13:14
1

Many of the command support a -whatif parameter that you could append and remove later. However, I have to say I like the comment idea better.

  • whatif is good, but not all commands support it – Keltari Jun 13 '13 at 20:02
1

This appears to work too, after some playing with invoke:

$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"

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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