21 February 2007

PowerShell Pearl: Filter by Contained Text

I have just recently started using PowerShell. While this blog will not be where you want to go to learn PowerShell, as I pick up little pearls here and there, I will try to share them with small samples and quick PowerShell scripts. I am no PowerShell expert, so if you find any errors, please let me know. 

Today's Pearl: 

If you are returning a set of results and you want to filter those results by text contained in one of the fields there are two ways I found you can do this. The first is using a Field.Contains(“search text”) –eq “true” and the other (thanks Scott) is doing a Field –match “search text”. 

So if you wanted to see all of the System Event logs that have cmd.exe is the message you could get this using either of these methods: 

Get-EventLog system | where { $_.Message.Contains("cmd.exe") -eq "true" }

or…

Get-EventLog system | where { $_.Message -match "cmd.exe" }

Either of these can be used in the negative form just as easily:

Get-EventLog system | where { $_.Message.Contains("cmd.exe") -eq "false" }

Get-EventLog system | where { $_.Message -notmatch "cmd.exe" }

That’s it! The –match and –notmatch are probably the easier of the two to use, although I am sure there is a reason for each of them that I am not aware of. Hopefully things like this will come to be part of my knowledge as I know more.

Update:

Okay, I just learned that -match and -nomatch are regular expression comparison operators. Another set comparison operators you could use are -like and -notlike. These are the wildcard comparison operators. It could be used like so:

Get-EventLog system | where { $_.Message -like "*cmd.exe*" }

Filed under: ,
 

Comments

No Comments
New Comments to this post are disabled