萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

PowerShell 將組件加入 GAC:直接呼叫 .NET API 免用 GacUtil

背景

傳統用 gacutil /i MyAssembly.dll,但 gacutil 屬於 Windows SDK,非 .NET Framework 內建,純 .NET 環境可能找不到。

PowerShell 純 .NET 解法


[Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") | Out-Null
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Full\Path\To\MyAssembly.dll")

原理解析

  • System.EnterpriseServices.Internal.Publish 類別封裝 GAC 操作
  • GacInstall(path) 將指定組件安裝至全域組件快取
  • GacRemove(assemblyName) 移除組件
  • 同類別也提供 RegAsm 相似功能 (註冊 COM Interop)

完整腳本範例


param(
    [Parameter(Mandatory=$true)]
    [string]$DllPath
)

if (-not (Test-Path $DllPath)) {
    Write-Error "找不到檔案: $DllPath"
    exit 1
}

try {
    [Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") | Out-Null
    $pub = New-Object System.EnterpriseServices.Internal.Publish
    $pub.GacInstall($DllPath)
    Write-Host "成功安裝至 GAC: $DllPath" -ForegroundColor Green
}
catch {
    Write-Error "安裝失敗: $_"
    exit 1
}

儲存為 Install-Gac.ps1,使用:.\Install-Gac.ps1 -DllPath ".\MyLib.dll"

注意事項

  • 需管理員權限執行 PowerShell
  • 組件必須有強名稱 (Strong Name)
  • .NET Core / .NET 5+ 不使用 GAC,改用 NuGet 套件管理
  • 僅適用 .NET Framework 專案
copyright © 萬盛學電腦網 all rights reserved