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

PowerShell格式化字符串传递参数未正常填充问题求助

解决PowerShell字符串格式化占位符未正确填充的问题

嘿,我来帮你搞定这个小问题!你的代码里的问题出在调用BuildReport时的参数传递方式上,咱们一步步拆解来看:

问题根源

在PowerShell里,逗号,是用来创建数组的运算符,可不是分隔函数参数的符号哦!你原来的代码里:

BuildReport $MyInvocation.MyCommand, 1, 2

这行代码相当于把$MyInvocation.MyCommand、1、2打包成一个数组,一股脑传给了BuildReport的第一个参数$functionName。剩下的$param1和$param2根本没接收到任何值,所以格式化字符串时才会出现:

You are in System.Object[]. Parameter expected is . Actual parameter is

修正后的代码

只需要把参数之间的逗号改成空格(PowerShell用空格分隔函数参数)就行:

function SendName(){ 
    BuildReport $MyInvocation.MyCommand 1 2  # 用空格分隔各个参数
} 

Function BuildReport($functionName, $param1, $param2){ 
    $report="You are in {0}. Parameter expected is {1}. Actual parameter is {2}" -f $functionName, $param1, $param2 
    write-host $report 
} 

SendName

运行结果

执行修正后的代码,你会得到符合预期的输出:

You are in SendName. Parameter expected is 1. Actual parameter is 2

小提示

  • 如果你确实需要把数组作为单个参数传递给函数,可以用@()包裹数组,比如BuildReport @($val1, $val2) $val3,这样第一个参数是数组,第二个参数是$val3。
  • PowerShell的参数传递默认是位置匹配,记得确保参数顺序和函数定义一致哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:14:21