无法在Windows 10中加载dll程序集(HRESULT异常:0x80131515)

时间:2016-10-08 19:51:58

标签: powershell dll scripting

我正在尝试加载JSON.NET的已编译dll程序集。但是我收到以下错误消息:

PS C:\Users\tamas\Desktop\garbage> Add-Type -path .\Newtonsoft.Json.dll
Add-Type : Could not load file or assembly 'file:///C:\Users\tamas\Desktop\garbage\Newtonsoft.Json.dll' or one of its d
ependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
At line:1 char:1
+ Add-Type -path .\Newtonsoft.Json.dll
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], FileLoadException
    + FullyQualifiedErrorId : System.IO.FileLoadException,Microsoft.PowerShell.Commands.AddTypeCommand

在另一台计算机上,在Windows 7下,我可以毫无问题地做同样的事情。 可能是什么原因和解决方案?

我的.NET版本:

PS C:\Users\tamas\Desktop\garbage> [System.Environment]::Version

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      30319  42000

PowerShell版本:

PS C:\Users\tamas\Desktop\garbage> $Host.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  206

2 个答案:

答案 0 :(得分:2)

感谢@ martin-brandl建议我能够找出问题(我实际上必须修改他的代码,因为它没有输出任何内容($global:error[0].Exception没有 LoaderExceptions 字段。))

PS C:\Users\tamas\Desktop\garbage>
>> try
>> {
>>     Add-Type -Path .\Newtonsoft.Json.dll
>> }
>> catch
>> {
>>         write-host $global:error[0].Exception.InnerException
>> }
System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused th
e assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enabl
e CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please ena
ble the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

事实证明,由于dll文件来自外部源,出于安全原因,powershell引发了异常。使用UnsafeLoadFrom(...)方法我可以加载dll程序集:

PS C:\Users\tamas\Desktop\garbage> [System.Reflection.Assembly]::UnsafeLoadFrom("c:\users\tamas\Desktop\garbage\Newtonso
ft.Json.dll") # absolute path required here!!

GAC    Version        Location
---    -------        --------
False  v4.0.30319     C:\Users\tamas\Desktop\garbage\Newtonsoft.Json.dll

有关此问题的更多信息,请访问msdn网站here

答案 1 :(得分:1)

我无法告诉你哪些依赖项缺失,但我可以告诉你如何找到它。只需将Add-Type try-catch范围内的LoaderException {@ 1}}包围,即可try { Add-Type -Path .\Newtonsoft.Json.dll } catch { $global:error[0].Exception.LoaderExceptions | % { Write-Host $_ } }

<body>