Powershell 在 Windows 10 上啟動緩慢

Powershell 在 Windows 10 上啟動緩慢

我在 Windows 10(版本 1703 - 創意者更新)上遇到 powershell 提示啟動緩慢的問題。

我的硬體規格(相當快的機器):Intel i5-7440HQ(四核心)/32GB DDR4 RAM/512 Samsung SSD 硬碟。

我嘗試繞過設定檔和執行策略,但它沒有改變任何內容:

powershell -noprofile -ExecutionPolicy 繞過 (Measure-Command { powershell "Write-Host 1" } ).TotalSeconds

6,228067

我朋友的同一台筆記型電腦安裝了 Windows 10,沒有創建者更新,在不到 0.5 秒的時間內運行了 powershell。

也嘗試使用 ngen.exe 進行一些編譯,但沒有幫助:

$env:path = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
[AppDomain]::CurrentDomain.GetAssemblies() | % {
  if (! $_.location) {continue}
  $Name = Split-Path $_.location -leaf
  Write-Host -ForegroundColor Yellow "NGENing : $Name"
  ngen install $_.location | % {"`t$_"}
}

知道如何調查這個問題嗎?

問候

答案1

這也發生在我身上 - 儘管可能不是最好的路線,添加powershell.exe到清單中Windows Defender 排除項將其速度從 20 秒加快到 < 1 秒。

使用舊版控制台、清除 PSReadLine 和運行 ngen 似乎根本沒有幫助。

答案2

我已經遇到同樣的問題相當長一段時間了,直到 PowerShell 啟動失敗並出現以下錯誤:

Exception:
System.OutOfMemoryException: Array dimensions exceeded supported range.
   at System.Collections.Generic.List`1.set_Capacity(Int32 value)
   at System.Collections.Generic.List`1.EnsureCapacity(Int32 min)
   at System.Collections.Generic.List`1.Add(T item)
   at System.IO.File.InternalReadAllLines(String path, Encoding encoding)
   at Microsoft.PowerShell.PSConsoleReadLine.<ReadHistoryFile>b__67_0()
   at Microsoft.PowerShell.PSConsoleReadLine.WithHistoryFileMutexDo(Int32 timeout, Action action)
   at Microsoft.PowerShell.PSConsoleReadLine.DelayedOneTimeInitialize()
   at Microsoft.PowerShell.PSConsoleReadLine.Initialize(Runspace runspace, EngineIntrinsics engineIntrinsics)
   at Microsoft.PowerShell.PSConsoleReadLine.ReadLine(Runspace runspace, EngineIntrinsics engineIntrinsics)
-----------------------------------------------------------------------

這讓我想到了現有的 Github 問題:https://github.com/Powershell/PSReadLine/issues/673

我嘗試刪除~\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\當時已超過 6 GB 的歷史文件,之後 PowerShell 控制台很快就開始開啟。

也許您遇到的緩慢是 PowerShell 試圖讀取一個大的歷史文件(該文件還不夠大,不足以導致OutOfMemory)。

答案3

可能還有其他原因導致 Powershell 啟動緩慢,但是總是對我來說速度變慢的原因是 Windows 更新。

ngen我想要做的是運行ngen update它來優化每個全域安裝的組件,而不是在每個組件 powershell 恰好已加載時運行:

. (Join-Path ([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) ngen.exe) update

更新到 2019 年 5 月 Win10 後,我發現效能有所提高

(measure-command { powershell.exe -command "1+1" }).TotalSeconds

從~1.35s 到~0.55s。

答案4

使用procmon(sysinternals 工具)分析powershell.exe 後,我可以看到該進程試圖在catroot2 資料夾中執行某些操作,因此在重命名它之後(您必須停止阻止該資料夾的CryptSvc 服務),它會自動建立。所以結論是該資料夾已損壞。 (對不起,我的英文不好)

執行下一個.bat

net stop CryptSvc /y
rename c:\windows\system32\catroot2 Catroot2.bak
net start CryptSvc

相關內容