More Fun with History

I blogged a few days ago about taking advantage of PowerShell’s history. As I was looking at the history object I noticed the ExecutionStatus property. Most of the time it should be “completed”. But what about commands that failed? Why not search my history buffer?

PS C:\> h (1..(h -count 1).id) | where {$_.ExecutionStatus -notmatch "completed"}  Id CommandLine  -- -----------  21 dir c:\test\test* | &$sb  27  &$executioncontext.InvokeCommand.NewScriptBlock($sb)  28 dir | &$executioncontext.InvokeCommand.NewScriptBlock($sb) 126 gwmi win32_bios -computer server01

Remember that ‘h’ is an alias for Get-History. The expression (h -count 1).id will return the id number for the last history item.

PS C:\> h (1..(h -count 1).id) | where {$_.ExecutionStatus -notmatch "completed"} |>> format-list ID,CommandLine,*time>>

Id                 : 21CommandLine        : dir c:\test\test* | &$sbStartExecutionTime : 7/18/2008 10:14:42 AMEndExecutionTime   : 7/18/2008 10:14:46 AM

Id                 : 27CommandLine        :  &$executioncontext.InvokeCommand.NewScriptBlock($sb)StartExecutionTime : 7/18/2008 10:16:04 AMEndExecutionTime   : 7/18/2008 10:16:13 AM

Id                 : 28CommandLine        : dir | &$executioncontext.InvokeCommand.NewScriptBlock($sb)StartExecutionTime : 7/18/2008 10:16:22 AMEndExecutionTime   : 7/18/2008 10:16:24 AM

Id                 : 126CommandLine        : gwmi win32_bios -computer server01StartExecutionTime : 7/18/2008 12:52:49 PMEndExecutionTime   : 7/18/2008 12:53:36 PM

I can also get a quick summary of how many expressions worked and how many failed:

PS C:\> h (1..(h -count 1).id) | Group ExecutionStatus

Count Name                      Group----- ----                      -----  130 Completed                 {1, 2, 3, 4...}    4 Stopped                   {21, 27, 28, 126}

Granted you may not need this kind of information on a daily basis but because PowerShell is all about objects its very easy to get if you need it.