首页 > 解决方案 > Powershell如何使用特殊字符传递参数

问题描述

我正在尝试将变量作为参数传递给 powershell 脚本。变量有一些特殊字符,调用 ps1 脚本失败。

在这里,我只是创建了一个示例来显示问题。

PS C:\>$pass1 = '?q$*9-W$wcx)O.Ra)X-&6'

PS C:\>powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command 'echo '$pass1''

错误:

At line:1 char:26
+ echo  ?q$*9s8ubhD8c-W$wcx)O.Ra9)DX-D&6
+                          ~
Unexpected token ')' in expression or statement.
At line:1 char:32
+ echo  ?q$*9s8ubhD8c-W$wcx)O.Ra9)DX-D&6
+                                ~
Unexpected token ')' in expression or statement.
At line:1 char:37
+ echo  ?q$*9s8ubhD8c-W$wcx)O.Ra9)DX-D&6
+                                     ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation
marks ("&") to pass it as part of a string.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

在此处输入图像描述

标签: powershell

解决方案


您的脚本有语法错误,参数/变量的实际值似乎没有问题。

这是有语法错误的行:

powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command 'echo '$pass1''

这是您的问题所在:

'echo '$pass1''

你实际上在这里传递了三件事......

  1. 'echo '
  2. $pass1
  3. ''

第二个单引号正在退出字符串。

您需要根据需要使用它们的方式在单字符串和双字符串之间交替:

$pass1 = '?q$*9-W$wcx)O.Ra)X-&6'
powershell -Command "echo '$pass1'"

推荐阅读