Powershell – Measure Historical Command

Have you ever been working in a Powershell console and have a command run longer than expected? Did you wish that you had wrapped that command in a Measure-Command so that you could view execution time? This has happened to me several times, so recently I started working on a Measure-HistoricalCommand function that would use Get-History to create a New-TimeSpan from the StartExecutionTime and EndExecutionTime properties. I would like to say thanks to @mtboren from vnugglets.com who helped add some functionality and speed up this function.


Function Measure-HistoricalCommand {
	param(
		## for getting info about the last X commands
		[parameter(Mandatory=$false,ParameterSetName="ByCommandCount")][alias("Count")][Int]$Last=1,
		## for getting info about a specific command ID
		[parameter(Mandatory=$true,ParameterSetName="ByCommandId")][alias("Id")][Int]$CommandID
	) ## end param

	process {
		## create the Get-History command expression to invoke; use -Id or -Count based on the params passed to this function
		$strGetHistoryExpr = "Get-History " + $(if ($CommandID) {"-Id $CommandID"} else {"-Count $Last"})
		Invoke-Expression $strGetHistoryExpr | %{
			$ts = New-TimeSpan -Start $_.StartExecutionTime -End $_.EndExecutionTime
			## again, take out the array, just return the object straight away
			#$myResults += New-Object PSObject -Property @{
			New-Object -TypeName PSObject -Property @{
				ID = $_.ID
				CommandLine = $_.CommandLIne
				EndExectuionTime = $_.EndExecutionTime
				StartExecutionTime = $_.StartExecutionTime
				TimeSpan = $ts
				TotalSec = $ts.TotalSeconds
			} ## end new-psobject
		} ## end History foreach-object
	} ## end process
} ## end fn
This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *