Reputation: 13
I'm trying to create a simple function based on the following by passing an argument to it. The function will search my command history looking for a string - the command works:
history | Where-Object {$_.CommandLine -match 'abc'}
From my research the closest thing to this would be:
Function FindHistory {history | Where-Object {$_.CommandLine -match '$args'}}
However I am unable to get this (or any variation) to work.
FindHistory abc
- should return all previous commands used with 'abc' in them.
What am I doing wrong?
btw, I've been an avid powershell user for all of 2 days - liking it :)
Upvotes: 2
Views: 110
Reputation: 68273
Using $args in a where-object clause is problematic.
Try this:
function findhistory ($search) {history | where-object {$_.CommandLine -match $search}}
Upvotes: 1
Reputation: 29450
Powershell won't expand variables in single quoted strings, so you have to use a double quoted string:
Function FindHistory {history | Where-Object {$_.CommandLine -match "$args"}}
Though $args
is an array of all arguments, so it may be more robust if you just specify a parameter:
Function FindHistory {PARAM($searchTerm) history | Where-Object {$_.CommandLine -match "$searchTerm"}}
Upvotes: 4