1

Having some trouble searching a log file. I have a basic script that searches for specific text in a log file. The problem is, I am trying to use variables that can be adjusted by the user at the command line but I cannot get them to be recognized. The script should output the results back to the screen.

param (
[string]$file ,
[string]$Ip ,
[string]$port
)
Get-Content -Path C:\$file | Where-Object {$_ -like $Ip -and $_ -like $port}

Example of command line to execute script:

PS C:\> .\LogSearch.ps1 logfile04.txt 192.168.1.7 21

In this case, logfile04.txt is the file, the port is 21 and the IP address is 192.168.1.7

At this point of running the script, I am returned with nothing, but there is that line within the file.

4|Oct 19 2015|18:28:39|106023|75.76.77.80|50077|192.168.1.7|21|Deny tcp src

James Pi
  • 71
  • 9
  • 1
    `-like` uses regex. If you type the IP and port surrounded in `*`, does it work? – Jacob Colvin May 04 '17 at 17:29
  • 1
    @MacroPower `-like` does not use regex that would be `-match`. [`-like` uses wildcards](https://msdn.microsoft.com/powershell/reference/5.1/Microsoft.PowerShell.Core/about/about_Wildcards) of which `*` is indeed one. – BenH May 04 '17 at 17:44
  • Using the `*` in the command line does work! I am now getting all of the lines with `192.168.1.7` instead of just the ones with port `21`. But I guess that is a different problem not relevant to this question. – James Pi May 04 '17 at 17:57

1 Answers1

1

The -like operator when used without a wildcard is the equivalent of -eq. Since your line doesn't both exactly equal 192.168.1.7 and 21 at the same time, it will never return. So if you wanted to use -like you will need to surround your match string with wildcards.

Get-Content -Path C:\$file | Where-Object {$_ -like "*$Ip*" -and $_ -like "*$port*"}

Alternatively, the -match operator uses regex. So you wouldn't need the wildcards.

Get-Content -Path C:\$file | Where-Object {$_ -match $Ip -and $_ -match $port}

Here is a good guide on the different uses of these comparison operators

BenH
  • 9,766
  • 1
  • 22
  • 35