You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell 5.1加载Newtonsoft.Json后Add-Type无法找到命名空间

问题原因与解决方案

问题原因

PowerShell会话中通过[Reflection.Assembly]::LoadFile加载的程序集,和Add-Type编译动态类型时的上下文是相互独立的。即使你能在PowerShell代码中直接调用[Newtonsoft.Json.JsonConverter],但Add-Type的C#代码块在编译时,默认不会自动关联已加载到会话中的程序集,因此编译器找不到Newtonsoft命名空间——本质是编译阶段缺少明确的程序集引用。

解决方法

你需要在Add-Type命令中显式指定要引用的Newtonsoft.Json程序集,或者在C#代码块内通过指令引用,以下是两种可行方案:

方案一:通过-ReferencedAssemblies参数指定程序集

先加载程序集并保存引用,再在Add-Type时传入该引用:

# 加载Newtonsoft.Json程序集
$jsonDllPath = "C:\Users\user\Documents\WindowsPowerShell\Modules\newtonsoft.json\1.0.2.201\libs\Newtonsoft.Json.dll"
$jsonAssembly = [System.Reflection.Assembly]::LoadFile($jsonDllPath)

# 定义自定义BigIntegerConverter类,显式引用程序集
Add-Type -ReferencedAssemblies $jsonAssembly -TypeDefinition @"
using System;
using System.Numerics;
using Newtonsoft.Json;

public class BigIntegerConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(BigInteger);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value == null ? null : BigInteger.Parse(reader.Value.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }
}
"@

方案二:在C#代码块内使用#r指令引用程序集

直接在C#代码开头添加程序集引用指令,无需单独传递参数:

Add-Type -TypeDefinition @"
#r "C:\Users\user\Documents\WindowsPowerShell\Modules\newtonsoft.json\1.0.2.201\libs\Newtonsoft.Json.dll"
using System;
using System.Numerics;
using Newtonsoft.Json;

public class BigIntegerConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(BigInteger);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value == null ? null : BigInteger.Parse(reader.Value.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString());
    }
}
"@

补充说明

两种方案的核心都是让Add-Type的编译上下文能找到Newtonsoft.Json的程序集。如果你的PowerShell版本较旧,#r指令可能不生效,优先使用方案一。

内容的提问来源于stack exchange,提问作者MegaBomber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:52:58