Yes, pwsh
tends to be slow.
Check your profiles.
It's better for startup time only one to exist. Some apps (like conda
) like to add something to a shared profile. Clean if something is not yours.
$profile | Select-Object -Property *
Use Runspaces to make your module imports lazily loaded. We can import a module in a different (background) thread and then use that already loaded module in our session. Look at the code below:
$LazyLoadProfileRunspace = [RunspaceFactory]::CreateRunspace()
$LazyLoadProfile = [PowerShell]::Create()
$LazyLoadProfile.Runspace = $LazyLoadProfileRunspace
$LazyLoadProfileRunspace.Open()
[void]$LazyLoadProfile.AddScript({Import-Module posh-git}) # (1)
[void]$LazyLoadProfile.BeginInvoke()
$null = Register-ObjectEvent -InputObject $LazyLoadProfile -EventName InvocationStateChanged -Action {
Import-Module -Name posh-git # (2)
$global:GitPromptSettings.DefaultPromptPrefix.Text = 'PS '
$global:GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n'
$LazyLoadProfile.Dispose()
$LazyLoadProfileRunspace.Close()
$LazyLoadProfileRunspace.Dispose()
}
As you can notice we have to describe modules we want to lazy load twice. First time for a background thread that will be actually loading it and the second for our actual thread. Ofc don't forget to clean things up at the end (close & dispose used).
This method is applicable only for modules or global variables - all your background thread-local variables/functions/etc won't come to your console session.
Note: It is a workaround. It's not truly lazy - we just put things with heavy time impact in the background and when it's ready we start using it (It's more of delayed initialization). That's why if you have something you need to use immediately after the shells console pop-up then you shouldn't use this technique.
Optional 1: For further investigation you can use PSProfiler.
Install-Module PSProfiler
Import-Module PSProfiler
Measure-Script -Top 3 $profile
Optional 2. Generate native images. This one didn't help me, but helped others. You need to have Visual Studio installed and run the code below in Developer Powershell for VS 20xx
with Admin permissions:
$env:PATH = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
[AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object {
$path = $_.Location
if ($path) {
$name = Split-Path $path -Leaf
Write-Host -ForegroundColor Yellow "`r`nRunning ngen.exe on '$name'"
ngen.exe install $path /nologo
}
}
Optional 3. Add powershell.exe
and pwsh.exe
or both to Windows Defender exclusions. Didn't help me but helped others.