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

VBScript调用PowerShell传递JSON变量时引号丢失及调用错误求助

解决VBScript调用PowerShell提交JSON的问题

一、确认VBScript调用PowerShell的正确方式

VBScript中调用PowerShell需使用WScript.Shell的Run或Exec方法,核心是处理好路径、参数的引号包裹和执行策略:

Set objShell = CreateObject("WScript.Shell")
' PowerShell路径(系统默认路径可直接用powershell.exe)
strPSPath = "powershell.exe"
' 你的PowerShell脚本绝对路径
strScript = "C:\Scripts\SubmitTicket.ps1"

' 后续会处理JSON参数,先占位
strJsonParam = ""

' 拼接命令:启用执行策略、指定脚本、传递参数
strCommand = strPSPath & " -ExecutionPolicy Bypass -File """ & strScript & """ -JsonPayload """ & strJsonParam & """"

' 执行命令,0表示后台运行,True表示等待执行完成
objShell.Run strCommand, 0, True

注意:

  • 必须添加-ExecutionPolicy Bypass,避免系统默认的脚本执行限制
  • 脚本路径和参数都要用""包裹(VBScript中双引号转义为两个双引号),防止路径/参数含空格时出错

二、解决JSON参数引号丢失的问题

命令行传递JSON时,双引号会被解析器逐层剥离,导致PowerShell无法识别完整参数。有两种可靠解决方法:

方法1:双重转义JSON中的双引号

在VBScript中,先将JSON里的每个"替换为""""(四层双引号),再包裹到参数的引号中:

' 原始JSON内容
strOriginalJson = "{""TicketID"":""INC12345"",""Title"":""系统监控告警"",""Description"":""CPU使用率超过90%""}"
' 双重转义双引号
strEscapedJson = Replace(strOriginalJson, """", """""")

' 拼接最终命令
strCommand = strPSPath & " -ExecutionPolicy Bypass -File """ & strScript & """ -JsonPayload """ & strEscapedJson & """"

对应的PowerShell脚本需正确接收参数:

param(
    [Parameter(Mandatory=$true)]
    [string]$JsonPayload
)

' 将字符串转为JSON对象并提交
$ticketData = $JsonPayload | ConvertFrom-Json
Invoke-RestMethod -Uri "https://your-service-api.com/tickets" -Method Post -Body ($ticketData | ConvertTo-Json) -ContentType "application/json"

方法2:通过标准输入传递JSON(推荐长JSON场景)

避免命令行参数长度限制和引号解析问题,直接将JSON写入PowerShell的标准输入:
VBScript代码:

Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("powershell.exe -ExecutionPolicy Bypass -File """ & strScript & """")

' 写入JSON内容到PowerShell标准输入
objExec.StdIn.WriteLine strOriginalJson
objExec.StdIn.Close

' 可选:读取执行结果
strResult = objExec.StdOut.ReadAll()
WScript.Echo strResult

PowerShell脚本读取标准输入:

' 从标准输入读取JSON
$jsonPayload = [Console]::In.ReadToEnd() | ConvertFrom-Json

' 提交请求
Invoke-RestMethod -Uri "https://your-service-api.com/tickets" -Method Post -Body ($jsonPayload | ConvertTo-Json) -ContentType "application/json"

补充:VBScript直接POST JSON的排查建议

如果想回到VBScript直接提交,可尝试以下修复:

  • 升级到MSXML6(替换msxml3.dll为Msxml2.XMLHTTP.6.0)
  • 明确设置Content-Type请求头
  • 检查代理或SSL证书信任问题
Set objHttp = CreateObject("Msxml2.XMLHTTP.6.0")
objHttp.Open "POST", "https://your-service-api.com/tickets", False
objHttp.SetRequestHeader "Content-Type", "application/json"
objHttp.Send strOriginalJson

If objHttp.Status = 200 Then
    WScript.Echo "提交成功:" & objHttp.ResponseText
Else
    WScript.Echo "错误:" & objHttp.Status & " - " & objHttp.StatusText
End If

内容的提问来源于stack exchange,提问作者Graham Van der vaart

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 09:20:12