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
  • <p>hi</p> <p>thank for sharing</p> <p>here another option:</p> <p>PS II&gt; (h)[-1].CommandLine</p> <p>Or another option</p> <p>PS II&gt; gc c:\scripts\history\f.ps1</p> <p>function lastCommand([switch]$Run) {</p> <p> &nbsp; $cmd=history | select -last 1</p> <p> &nbsp; if($Run) { </p> <p> &nbsp; &nbsp; &nbsp;iex $cmd </p> <p> &nbsp;}else {</p> <p> &nbsp; &nbsp; new-object psobject -prop @{</p> <p> &nbsp; &nbsp; &nbsp; &nbsp;command = $cmd.CommandLine</p> <p> &nbsp; &nbsp; &nbsp; &nbsp;Runtime = ($cmd.EndExecutionTime - $cmd.StartExecutionTime).Milliseconds</p> <p> &nbsp; &nbsp; &nbsp; &nbsp;Status = $cmd.ExecutionStatus</p> <p> &nbsp; &nbsp; }</p> <p> &nbsp; }</p> <p>}</p> <p>PS II&gt; . c:\scripts\history\f.ps1</p> <p>PS II&gt;</p> <p>PS II&gt; lastCommand</p>

  • <p>@Walid Toumi these are great suggestions. Thanks for sharing. </p>

  • <p>This seems to give me the last parameter of the last command:</p> <p>If I do this:</p> <p>gci Filesystem::N:\</p> <p>$$</p> <p>I get:</p> <p>Filesystem::N:\</p> <p>Similarly:</p> <p>gci Filesystem::N:\IT\Operations\Checklists\Sqlserver\ | select Fullname</p> <p>$$</p> <p>Gives:</p> <p>Fullname</p> <p>Is that what you&#39;d expect?</p> <p>Matt</p>

  • <p>@salisbury_matt</p> <p>&quot;Is that what you&#39;d expect?&quot;</p> <p>PS II&gt; help about_automatic_variables &nbsp;| Select-String -Simple &#39;$$&#39; -Context 0,4</p> <p>the function lastcommand return entire expression</p>

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