Last active
September 20, 2024 13:45
-
-
Save Calvindd2f/722f4b0bf11059fd95249fa77588bdb6 to your computer and use it in GitHub Desktop.
Optimize Assemblies & generate native .NET images for CPU
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # generate native .NET images for CPU | |
| function Optimize-Assemblies { | |
| [CmdletBinding()] | |
| param ( | |
| [string]$AssemblyFilter = "Microsoft.PowerShell.", | |
| [string]$Activity = "Native Image Installation" | |
| ) | |
| try { | |
| # Try to get ngen.exe from the Visual Studio environment | |
| $ngenPath = Get-Command ngen.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source | |
| # If not found, fallback to .NET Framework directory | |
| if (-not $ngenPath) { | |
| $ngenPath = 'C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\ngen.exe' | |
| } | |
| # Check if ngen.exe exists | |
| if (-not (Test-Path $ngenPath)) { | |
| Write-Error "Ngen.exe not found. Make sure .NET Framework is installed and the Visual Studio environment is loaded." | |
| return | |
| } | |
| Write-Verbose "Using ngen.exe from: $ngenPath" | |
| # Get a list of loaded assemblies | |
| $assemblies = [AppDomain]::CurrentDomain.GetAssemblies() | |
| # Filter assemblies based on the provided filter | |
| $filteredAssemblies = $assemblies | Where-Object { $_.FullName -like "$AssemblyFilter*" } | |
| if ($filteredAssemblies.Count -eq 0) { | |
| Write-Warning "No matching assemblies found for optimization." | |
| return | |
| } | |
| $totalAssemblies = $filteredAssemblies.Count | |
| $currentAssembly = 0 | |
| foreach ($assembly in $filteredAssemblies) { | |
| $currentAssembly++ | |
| # Get the name of the assembly | |
| $name = [System.IO.Path]::GetFileName($assembly.Location) | |
| # Display progress | |
| $percentComplete = ($currentAssembly / $totalAssemblies) * 100 | |
| Write-Progress -Activity $Activity -Status "Optimizing $name" -PercentComplete $percentComplete | |
| # Run ngen install | |
| $output = & $ngenPath install $assembly.Location 2>&1 | |
| # Check for errors | |
| if ($LASTEXITCODE -ne 0) { | |
| Write-Warning "Error optimizing $name. Error: $output" | |
| } | |
| else { | |
| Write-Verbose "Successfully optimized $name" | |
| } | |
| } | |
| } | |
| catch { | |
| Write-Error "An error occurred: $_" | |
| } | |
| finally { | |
| Write-Progress -Activity $Activity -Completed | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment