PowerShell 使用 Add-Type 參照自製 .NET 程式庫時發生無法載入錯誤。

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
At D:\pslab\AddTypeTest.ps1:1 char:1
+ Add-Type -Path .\FooLibrary.dll
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeCommand

訊息未明說載入失敗原因,只說「詳見 LoaderExceptions」,在 PowerShell 中要如何查看呢?做法不難,用 try 將 Add-Type 包起來,在 catch 中印出 $.Exception.LoaderException 即可,由此得知載入失敗原因是找不到 Json.NET:

跟 .NET 不一樣,PowerShell 不會自動帶入程式庫參照的其他程式庫,除了複製 Newtonsoft.Json.dll,還得 Add-Type -Path Newtonsoft.Json.dll。但我發現一個疑點,除了 Json.NET,FooLibrary.dll 同時也參照了 Managed ODP.NET,沒 Add-Type -Path Oracle.ManagedDataAccess.dll 卻沒出錯。

實驗發現,這是因為我在 FooLibrary 有型別繼承 JsonConverter,故 Add-Type 時就需參照 Json.NET;沒參照 Managed ODP.NET 雖然 Add-Type 不會出錯 ,要等到呼叫引用它的方法才會爆炸:

就這樣,又累積了一點 PowerShell 引用 .NET 程式庫時處理相依組件的冷知識。

Tips of adding referenced assmblies when Add-Type .NET library.


Comments

Be the first to post a comment

Post a comment