PowerTip: Find the Last Command PowerShell Ran

PowerTip: Find the Last Command PowerShell Ran

  • Comments 5
  • Likes

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.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • 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:



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




    Is that what you'd expect?


  • @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.