Repository navigation
Expand file tree
/
Copy pathProfileDiagnostics.ps1
More file actions
73 lines (63 loc) · 2.52 KB
/
Copy pathProfileDiagnostics.ps1
File metadata and controls
73 lines (63 loc) · 2.52 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<#
.SYNOPSIS
Profile startup diagnostics with timing information.
.DESCRIPTION
When the environment variable PROFILE_DIAGNOSTICS is set to "1" or "true",
this module logs timestamped messages during profile startup to a temp file.
After the profile loads, it tells you where the log file is.
Usage:
$env:PROFILE_DIAGNOSTICS = "1"
# Start a new PowerShell session
# The log file path will be displayed after startup completes.
#>
$Global:__ProfileDiagnostics = @{
Enabled = $false
LogFile = $null
StartTime = $null
}
function Initialize-ProfileDiagnostics {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseSingularNouns', '',
Justification = 'Diagnostics is a mass noun; the singular form reads wrong.')]
param()
$enabled = $env:PROFILE_DIAGNOSTICS
if ($enabled -eq '1' -or $enabled -eq 'true') {
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$logFile = Join-Path ([System.IO.Path]::GetTempPath()) "pwsh-profile-$timestamp.log"
$Global:__ProfileDiagnostics.Enabled = $true
$Global:__ProfileDiagnostics.LogFile = $logFile
$Global:__ProfileDiagnostics.StartTime = [System.Diagnostics.Stopwatch]::StartNew()
Write-ProfileLog 'Profile startup begin'
}
}
function Write-ProfileLog {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)]
[string]$Message
)
if (-not $Global:__ProfileDiagnostics.Enabled) {
return
}
$elapsed = $Global:__ProfileDiagnostics.StartTime.Elapsed.TotalMilliseconds
$entry = '[{0,8:F1}ms] {1}' -f $elapsed, $Message
Add-Content -Path $Global:__ProfileDiagnostics.LogFile -Value $entry
}
function Complete-ProfileDiagnostics {
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseSingularNouns', '',
Justification = 'Diagnostics is a mass noun; the singular form reads wrong.')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingWriteHost', '',
Justification = 'Reports the log location to the interactive host at startup.')]
param()
if (-not $Global:__ProfileDiagnostics.Enabled) {
return
}
Write-ProfileLog 'Profile startup complete'
$Global:__ProfileDiagnostics.StartTime.Stop()
$total = $Global:__ProfileDiagnostics.StartTime.Elapsed.TotalSeconds
Write-Host "Profile loaded in $([math]::Round($total, 2))s. Diagnostics log: $($Global:__ProfileDiagnostics.LogFile)" -ForegroundColor Cyan
}