如何向PowerShell脚本传递包含引号等特殊字符的字符串参数
解决方案
第一步:优化脚本参数接收逻辑
先把原有脚本改成显式参数接收,避免$args的自动解析异常,修改后的C:\temp\myscript.ps1内容如下:
# 显式声明接收第一个位置参数 param( [Parameter(Position=0)] [string]$mystring ) # 空值校验避免后续报错 if (-not $mystring) { Write-Error "未传入有效字符串" exit 1 } # 原有处理逻辑,正则改用单引号包裹避免内部双引号转义冲突 $result = $mystring | Select-String -Pattern 'DisplayName="(.*?)"' $group = $result.Matches.Groups[1].Value $group | Out-File C:\temp\group.txt -Encoding UTF8
第二步:选择传参方案
方案1:手动转义调用(适合简单场景)
从外部调用powershell.exe时,字符串内部的双引号需要用\转义(CMD调用场景),同时外层用双引号包裹整个字符串:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -c C:\temp\myscript.ps1 "<转义后的特殊字符串>"
缺陷:你的字符串包含多层嵌套引号、XML转义符,手动转义容易出错,更推荐方案2。
方案2:Base64编码传参(推荐,完全规避转义问题)
PowerShell原生支持执行Base64编码的UTF16-LE格式命令,你可以先把需要传入的字符串和执行逻辑编码成Base64字符串,直接调用即可,完全不用处理任何特殊字符转义:
- 先在PowerShell中运行以下代码生成最终调用命令:
# 替换为你实际要传入的原始特殊字符串 $inputStr = @" <UserInputs><UserInput Question="Gruppenname" Answer="<Values Count="1"><Value DisplayName="Humanresources" Id="af05c5d3-2312-c897-8439-08979d4d0a49" /></Values>" Type="System.SupportingItem.PortalControl.InstancePicker" /><UserInput Question="Ausgabe" Answer="Namen" Type="richtext" /></UserInputs> "@ # 拼接完整执行命令,处理单引号转义 $command = "C:\temp\myscript.ps1 '$($inputStr.Replace("'","''"))'" # 转换为符合PowerShell要求的Base64编码 $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $base64Cmd = [Convert]::ToBase64String($bytes) # 输出最终可直接运行的调用命令 Write-Host "最终调用命令:" Write-Host "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -EncodedCommand $base64Cmd"
- 直接运行上一步输出的调用命令即可,所有特殊字符都会完整正确传递到脚本中。
验证
执行完成后查看C:\temp\group.txt,即可看到提取到的Humanresources值。
内容的提问来源于stack exchange,提问作者rolfderwolf
相关产品推荐
相关产品推荐

