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

传递字符串至PowerShell脚本时遇Unexpected token '}'错误的解决方法

问题描述

我有一个PowerShell脚本,参数定义如下:

Param
(
    [switch] $enable,
    [string] $arg1,
    [string] $arg2
)

脚本接受两个字符串参数,每个字符串以|-|作为分隔符,第二个字符串可包含除'外的任意字符。调用脚本的命令如下:

PowerShell .\script.ps1 -arg1 'Hello|-|World' -arg2 'random|-|dwua0928]43d}'

此时字符}和分隔符中的-都会触发错误,报错信息如下:

At line:1 char:54
+ .\Script.ps1 -arg2 <redacted>|-|<redacted> ...    
+                                ~
Missing expression after unary operator '-'.
At line:1 char:53
+ .\Script.ps1 -arg1 <redacted>|-|<redacted> ...    
+                               ~
Expressions are only allowed as the first element of a pipeline.

即使将分隔符改为/-/,}仍会引发错误,报错信息如下:

At line:1 char:168
+ ... <redacted>/-/<redacted>!OW}:Lj<redacted> ...
+                               ~
Unexpected token '}' in expression or statement.
At line:1 char:181
+ ... /-/<redacted>cO0}e]k<redacted> ...
+                     ~
Unexpected token '}' in expression or statement.
解决方案

问题核心是在外部环境(如cmd.exe)调用PowerShell时,单引号无法阻止PowerShell解析内部的特殊语法字符,导致-、}这类字符被当作表达式的一部分处理,触发语法错误。以下是三种可行的解决方法:

1. 用双引号包裹参数(cmd环境下推荐)

将参数值用双引号包裹,PowerShell会将整个双引号内的内容视为完整字符串,不会解析内部的特殊字符:

PowerShell .\script.ps1 -arg1 "Hello|-|World" -arg2 "random|-|dwua0928]43d}"

如果参数内包含双引号,需要用\"转义,例如:"abc\"def"。

2. 使用-Command参数嵌套引号

通过-Command参数,用外层双引号包裹整个调用命令,内层用单引号定义参数值,确保PowerShell正确识别字符串边界:

PowerShell -Command ".\script.ps1 -arg1 'Hello|-|World' -arg2 'random|-|dwua0928]43d}'"

3. 直接在PowerShell终端内调用

如果是在PowerShell原生环境中执行脚本,直接运行命令即可——PowerShell原生支持单引号字符串,不会解析内部的特殊字符:

.\script.ps1 -arg1 'Hello|-|World' -arg2 'random|-|dwua0928]43d}'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:45:47