我正在尝试通过向其传递参数来基于以下内容创建一个简单的函数。该函数将搜索我的命令历史记录以查找字符串 - 命令有效:
history | Where-Object {$_.CommandLine -match 'abc'}
从我的研究中,最接近这一点的是:
Function FindHistory {history | Where-Object {$_.CommandLine -match '$args'}}
但是我无法让这个(或任何变化)起作用。
FindHistory abc
- 应该返回与'abc'一起使用的所有先前命令。
我做错了什么?
顺便说一句,我在2天内都是狂热的PowerShell用户 - 喜欢它:))
答案 0 :(得分:4)
Powershell不会在单引号字符串中扩展变量,因此您必须使用双引号字符串:
Function FindHistory {history | Where-Object {$_.CommandLine -match "$args"}}
虽然$args
是所有参数的数组,但如果只指定参数,它可能会更健壮:
Function FindHistory {PARAM($searchTerm) history | Where-Object {$_.CommandLine -match "$searchTerm"}}
答案 1 :(得分:1)
在where-object子句中使用$ args是有问题的。
试试这个:
function findhistory ($search) {history | where-object {$_.CommandLine -match $search}}