Public/Get-Chronometer.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function Get-Chronometer
{
    <#
        .Description
        Loads a script and then tracks the line by line execution times

        .Example
        Get-Chronometer -Path .\example.ps1 -Script {
            .\example.ps1
        }
    #>

    [CmdletBinding()]
    param(
        # Script file to measure execution times on
        [Parameter(Position=0)]
        [string[]]
        $Path,

        # Line numbers within the script file to measure
        [int[]]
        $LineNumber = $null,

        # The script to start the scrupt or execute other commands
        [Parameter(Position=1)]
        [alias('Script','CommandScript')]
        [scriptblock]
        $ScriptBlock
    )

    $Chronometer = [Chronometer]::New()

    Write-Verbose "Setting breapoints"
    $Chronometer.AddBreakpoint($Path,$LineNumber)

    if($null -ne $Chronometer.breakPoint -and $null -ne $ScriptBlock)
    {
        Write-Verbose "Executing Script"
        [ScriptProfiler]::Start()
        [void] $ScriptBlock.Invoke()

        Write-Verbose "Clearing Breapoints"
        $Chronometer.ClearBreakpoint()

        Write-Verbose "Processing data"
        foreach($node in [ScriptProfiler]::Queue.GetEnumerator())
        {
            $Chronometer.AddExecution($node)
        }

        Write-Output $Chronometer.GetResults()
    }
    else
    {
        Write-Warning "Parsing files did not result in any breakpoints"
    }
}