PowerShell中JQ的SELECT语句使用变量无法运行如何解决?
PowerShell中调用jq时变量不生效的解决方案
问题根因
- PowerShell语法规则中,单引号包裹的字符串不会解析内部的$变量,你写的
$host_name会作为字面量直接传给jq,导致匹配失败 - 你代码里用的
\"转义方式不符合PowerShell的转义规则,也会引发jq语法错误
推荐解决方案(无转义坑,兼容性最好)
用jq内置的--arg参数从外部传入PowerShell变量值,不需要处理任何引号转义:
首先定义你的目标变量,示例:$host_name = "test1"
再执行OCI命令:
oci compute instance list-vnics --all --compartment-id xxxxx --profile myprof | C:\myfiles\jq-win64.exe --arg target_host "$host_name" '.data[]|select(."hostname-label" == $target_host)'
说明:--arg target_host "$host_name"的作用是把PowerShell中$host_name的取值传递给jq内部的$target_host变量,完全规避PowerShell和jq的引号规则冲突问题。
可选方案(直接展开PowerShell变量)
如果你需要直接在jq表达式内展开PowerShell变量,改用双引号包裹整个jq表达式,PowerShell中双引号内的双引号用反引号`转义即可:
oci compute instance list-vnics --all --compartment-id xxxxx --profile myprof | C:\myfiles\jq-win64.exe ".data[]|select(`"hostname-label`" == `"$host_name`")"
内容的提问来源于stack exchange,提问作者Safney
相关产品推荐
相关产品推荐

