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

PowerShell中--%存在时@Args无法展开?如何传递函数参数给程序

问题描述

直接运行 D:\program.exe this is a #full sentence 时,#full sentence 会被PowerShell当作注释丢弃,不想用引号包裹参数,于是尝试编写函数:

function global:note { 
  D:\program.exe  --% @Args
}

原本期望@Args展开传递参数,--%阻止参数解析,但实际@Args被当作字面量传递。去掉--%后@Args能展开,但参数仍会被解析,测试情况如下:

情况1

function global:note { 
  D:\program.exe @Args
}

在PowerShell提示符输入 note this is a #complete sentence,输出为:

this is a

情况2

function global:note { 
  D:\program.exe --% @Args
}

输入相同命令,输出为:

@Args

疑问

为什么--%存在时@Args无法展开?如何实现既传递完整函数参数又不被PowerShell解析?


原因与解决方案

原因

--%是PowerShell的参数结束符(stop-parsing symbol),一旦触发,PowerShell会停止解析后续所有内容,直接将文本原封不动传递给外部程序。因此@Args会被当作普通字符串,不会被展开为函数参数。

解决方案

方法1:提取原始命令行输入

通过$MyInvocation.Line获取完整的命令行内容,剔除函数名后传递给外部程序,确保所有字符(包括#)都被完整传递:

function global:note {
  # 去掉函数名及后面的空格,保留剩余所有内容
  $rawInput = $MyInvocation.Line -replace "^$($MyInvocation.InvocationName)\s*", ''
  D:\program.exe $rawInput
}

运行note this is a #complete sentence时,#complete sentence会被完整传递给program.exe,不会被截断。

方法2:拼接参数并绕过解析

将$Args中的参数用空格拼接后直接传递,避免PowerShell解析特殊字符:

function global:note {
  D:\program.exe ($Args -join ' ')
}

这种方法会把所有参数合并成一个字符串传递,同样能保留#等特殊字符,不会被当作注释截断。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:35:17