PowerTip: Find the Last Command PowerShell Ran

PowerTip: Find the Last Command PowerShell Ran

Rate This
  • Comments 5

Summary: Find the last Windows PowerShell command by using an automatic variable.

Hey, Scripting Guy! Question How can you find the last Windows PowerShell command that was run?

Hey, Scripting Guy! Answer Use the $$ automatic variable.

Leave a Comment
  • Please add 6 and 3 and type the answer here:
  • Post
  • hi

    thank for sharing

    here another option:

    PS II> (h)[-1].CommandLine

    Or another option

    PS II> gc c:\scripts\history\f.ps1

    function lastCommand([switch]$Run) {

      $cmd=history | select -last 1

      if($Run) {

         iex $cmd

     }else {

        new-object psobject -prop @{

           command = $cmd.CommandLine

           Runtime = ($cmd.EndExecutionTime - $cmd.StartExecutionTime).Milliseconds

           Status = $cmd.ExecutionStatus

        }

      }

    }

    PS II> . c:\scripts\history\f.ps1

    PS II>

    PS II> lastCommand

  • @Walid Toumi these are great suggestions. Thanks for sharing.

  • This seems to give me the last parameter of the last command:

    If I do this:

    gci Filesystem::N:\

    $$

    I get:

    Filesystem::N:\

    Similarly:

    gci Filesystem::N:\IT\Operations\Checklists\Sqlserver\ | select Fullname

    $$

    Gives:

    Fullname

    Is that what you'd expect?

    Matt

  • @salisbury_matt

    "Is that what you'd expect?"

    PS II> help about_automatic_variables  | Select-String -Simple '$$' -Context 0,4

    the function lastcommand return entire expression

  • Actually if you want the last command it would probably be the first token on the line so the automatic variable $^ should be used.

Page 1 of 1 (5 items)