PowerTip: Find the Last Command PowerShell Ran

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.

Comments (5)

  1. Greg Wojan says:

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

  2. Walid Toumi says:


    thank for sharing

    here another option:

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

    Or another option

    PS II> gc c:scriptshistoryf.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:scriptshistoryf.ps1

    PS II>

    PS II> lastCommand

  3. Ed Wilson says:

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

  4. salisbury_matt says:

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

    If I do this:

    gci Filesystem::N:


    I get:



    gci Filesystem::N:ITOperationsChecklistsSqlserver | select Fullname




    Is that what you'd expect?


  5. Walid Toumi says:


    "Is that what you'd expect?"

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

    the function lastcommand return entire expression

Skip to main content