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

PowerShell中如何将函数与参数同存变量后执行?

在PowerShell中如何将函数名与参数一同存储并调用?

你尝试的写法$cFunc = 'myFuncWithArgs' $temp属于语法错误,PowerShell无法识别这种将函数名和参数直接拼接赋值的方式。要实现将函数名与参数关联存储并执行的需求,有两种常用方案:

方案1:使用数组存储 + Splatting语法

将函数名和参数存入数组,调用时利用PowerShell的splatting特性展开数组,第一个元素作为函数名,剩余元素作为参数传递:

function myFuncWithArgs($arg) { 
    Write-Output $arg 
}

$temp = 'sometext'

# 存储函数名和对应参数
$cFunc = 'myFuncWithArgs', $temp
# 通过splatting调用(@符号展开数组)
& @cFunc

方案2:使用脚本块(ScriptBlock)封装

将函数调用逻辑封装成脚本块,调用时直接执行脚本块即可:

静态封装

function myFuncWithArgs($arg) { 
    Write-Output $arg 
}

$temp = 'sometext'

# 直接封装函数调用语句
$cFunc = { myFuncWithArgs $temp }
# 执行脚本块
& $cFunc

动态构建脚本块

如果需要更动态的参数拼接,可以用[scriptblock]::Create()生成脚本块:

function myFuncWithArgs($arg) { 
    Write-Output $arg 
}

$temp = 'sometext'

# 动态拼接函数调用字符串并转为脚本块
$cFunc = [scriptblock]::Create("myFuncWithArgs '$temp'")
# 执行脚本块
& $cFunc

两种方案都能实现你要的效果,数组+splatting更适合简单的参数传递场景,脚本块则支持更复杂的执行逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:17:08