PowerShell自定义函数hg传参失败:无法绑定Select-String的Pattern参数
解决PowerShell中
hg函数参数绑定问题 你的问题出在函数没有声明参数,导致传入的字符串无法赋值给$pattern变量,Select-String自然拿不到有效值。下面是两种修复方案:
方案1:显式声明参数(推荐)
这种方式更规范,还能强制要求传入参数,避免遗漏:
function hg { param( [Parameter(Mandatory=$true)] [string]$Pattern ) h | Select-String -Pattern $Pattern }
方案2:使用自动变量$args(快速实现)
如果只是简单需求,直接用$args[0]获取第一个传入的参数即可:
function hg { h | Select-String -Pattern $args[0] }
修复后执行hg "some string",就能正常过滤PowerShell历史命令中包含指定字符串的内容,和Linux的history | grep "string"效果一致。
内容的提问来源于stack exchange,提问作者Tester
相关产品推荐
相关产品推荐

