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

如何在PowerShell中将含特殊字符的JSON作为单个参数传给程序

在PowerShell中向C#控制台程序传递含特殊字符的JSON作为单个参数

以下是几种可靠的解决方法,避免JSON被拆分为多个参数:

1. 用单引号包裹完整JSON字符串

PowerShell中,单引号包裹的字符串会被视为原样文本,不会解析内部的双引号、空格或换行转义符(仅需将JSON内的单引号替换为两个连续单引号)。示例:

.\YourConsoleApp.exe '{"username": "Jane Doe", "description": "Line 1`nLine 2", "note": "it''s a test"}'

2. 借助PowerShell变量传递(推荐复杂JSON)

先将JSON存入变量,直接传递变量名即可,PowerShell会自动维护参数的完整性。对于多换行、多特殊字符的JSON,用Here-String定义变量更方便:

$jsonPayload = @"
{
  "product": "Laptop",
  "specs": {
    "ram": "16GB",
    "storage": "512GB SSD"
  },
  "remarks": "This is a
multi-line remark with spaces."
}
"@
.\YourConsoleApp.exe $jsonPayload

3. 手动转义双引号(仅适合简单JSON)

用双引号包裹JSON时,需将内部所有双引号用反引号`转义,这种方式容易出错,仅推荐短JSON:

.\YourConsoleApp.exe "{`"product`": `"Mouse`", `"price`": 29.99}"

C#端接收代码示例

在控制台程序的Main方法中,直接通过args数组获取完整JSON:

using System;

namespace YourConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No JSON parameter received.");
                return;
            }
            
            string receivedJson = args[0];
            Console.WriteLine("Received JSON content:");
            Console.WriteLine(receivedJson);
            // 此处添加JSON解析或业务逻辑
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:17:14