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

PowerShell 7.2中如何从命令行传递Hashtable类型参数?

解决PowerShell 7.2中通过pwsh命令传递Hashtable参数类型不匹配的问题

问题原因

当通过pwsh可执行文件(无论是从外部终端如cmd/bash,还是从另一个PowerShell进程)调用脚本时,直接传递的哈希表字面量@{...}会被当作纯字符串传递,而非被解析为Hashtable对象。这是因为跨进程参数传递本质是字符串传递,目标PowerShell会话不会自动解析PowerShell语法元素(如哈希表字面量),导致参数类型转换失败。

解决方案

根据调用环境的不同,有两种可靠的解决方式:

1. 从PowerShell进程内调用pwsh

使用-Command参数将整个调用逻辑包裹为PowerShell脚本块,让目标会话解析哈希表语法:

pwsh -Command ".\ScriptName.ps1 -TestTable @{Test='This is a test'}"

注意:内部字符串使用单引号避免被当前PowerShell会话提前解析;如果必须用双引号,需转义为"或""。

2. 从外部终端(如cmd)调用pwsh

需要将哈希表语法用引号包裹,并转义特殊字符:

pwsh -Command ".\ScriptName.ps1 -TestTable @{Test=`"This is a test`"}"

或者使用单引号避免转义:

pwsh -Command ".\ScriptName.ps1 -TestTable @{Test='This is a test'}"

补充:复杂对象的序列化传递

如果哈希表结构复杂,可通过JSON序列化传递,再在目标脚本中还原为Hashtable:
调用端(PowerShell内):

$sourceHash = @{Test = "This is a test"; Nested = @{Key = "Value"}}
$json = $sourceHash | ConvertTo-Json -Compress
pwsh -Command ".\ScriptName.ps1 -TestTable (`$json | ConvertFrom-Json -AsHashtable)"

验证方法

修改脚本添加类型输出,确认参数类型正确:

#requires -version 7.2

[CmdletBinding(PositionalBinding = $False)]
param ([hashtable] $TestTable)

$TestTable.GetType().FullName
$TestTable

正确传递后,会输出System.Collections.Hashtable及哈希表内容,而非字符串类型的报错信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 07:42:36