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

使用-File选项调用PowerShell脚本时,如何解决参数引号问题?

解决cmd中PowerShell -File调用脚本时JSON参数截断问题

问题核心

在Windows cmd中使用PowerShell -File调用脚本时,传递包含空格和双引号的JSON参数会被截断(仅收到'{"lastname":'),但在PowerShell控制台或不使用-File参数时调用正常。

原因分析

使用-File参数时,PowerShell直接采用cmd的参数解析规则:cmd会将空格视为参数分隔符,原写法中的转义方式无法让cmd识别整个JSON为单个参数,导致空格后的部分被当作新参数。

有效解决方案

方案1:cmd内正确转义双引号

在cmd中,用双引号包裹整个JSON参数,内部双引号用^(cmd的转义符)转义:

PowerShell -File "C:\work\LV Demo\http-patch.ps1" -ReqURL myRESTApi -JSONString "{^"lastname^": ^"Bunny^"}"

或者用双引号嵌套(cmd中""表示单个双引号):

PowerShell -File "C:\work\LV Demo\http-patch.ps1" -ReqURL myRESTApi -JSONString "{`"lastname`": `"Bunny`"}"

方案2:改用-Command参数调用

通过-Command参数,使用PowerShell自身的语法规则传递参数,避免cmd的解析干扰:

PowerShell -Command "& 'C:\work\LV Demo\http-patch.ps1' -ReqURL myRESTApi -JSONString '{\"lastname\": \"Bunny\"}'"

也可以用单引号包裹JSON(PowerShell中单引号内的内容不会被解析),cmd中两个单引号表示单个单引号:

PowerShell -Command "& 'C:\work\LV Demo\http-patch.ps1' -ReqURL myRESTApi -JSONString ''{'lastname': 'Bunny'}''"

方案3:通过文件传递JSON(适合复杂场景)

如果JSON内容较长或格式复杂,可将JSON写入文件,让脚本读取文件内容:

  1. 创建data.json,内容为:
    {"lastname": "Bunny"}
    
  2. 修改脚本支持读取文件:
    param($ReqURL, $JSONPath) 
    $JSONString = Get-Content $JSONPath -Raw
    Write-Host $ReqURL
    Write-Host $JSONString
    Invoke-RestMethod -Uri $ReqURL -Method Patch -ContentType "application/json" -Body $JSONString
    
  3. cmd调用:
    PowerShell -File "C:\work\LV Demo\http-patch.ps1" -ReqURL myRESTApi -JSONPath "C:\work\LV Demo\data.json"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:15:44