none
parsing text file using powershell RRS feed

  • Question

  • Hi

    I am trying to extract ONLY the IP addresses in a DNS log file.  There are different IP addresses in the file. I managed to extract some data but that depends on the pattern that I am supplying, see command below

    Select-String -Path .\dns.log "snd*" | %{$_.line.split()} | Select-String "192.*"| Select-Object -Unique

    Select-String -Path .\dns.log "snd*" | %{$_.line.split()} | Select-String "10.*"| Select-Object -Unique

     

    any help would be appreciated

    mjksgea

    Wednesday, April 15, 2015 2:53 PM

Answers

  • Did you change the path to the location of your log file? I created a test one on my C drive and pasted in the contents of your sample, it seemed to work pretty well - 

    PS C:\powershell> $pattern = "([0-9]{1,3}\.){3}[0-9]{1,3}"
    $ips = @()
    gc  C:\dns.log | % {
    
    if (($_ -match $pattern)) {
    
    $ips += [regex]::Match($_, $pattern).Value
    
    }
    
    }
    $ips
    10.10.30.21

    • Marked as answer by mjksgea Thursday, April 16, 2015 10:01 AM
    Thursday, April 16, 2015 9:48 AM

All replies

  • You can use regex, I'm not 100% sure of the contents of the log file as I haven't seen it but this will extract IP's

    $pattern = "([0-9]{1,3}\.){3}[0-9]{1,3}"
    $ips = @()
    gc  <dns.log path> | % {
    
    if (($_ -match $pattern)) {
    
    $ips += [regex]::Match($_, $pattern).Value
    
    }
    
    
    }
    
    

    Thursday, April 16, 2015 8:20 AM
  • Hi

    there is an error with the word path.  removing it and running the script i get nothing, so I presume the $pattern needs changing, I am not familair with regex.

    A sample of the file

    09/04/2015 16:45:46 0574 PACKET  00000000055FFC60 UDP Rcv 10.10.30.21    f37b   Q [0001   D   NOERROR] A      (8)servername(5)Xsomthing(2)somthing(2)com(0)

    regards

    Thursday, April 16, 2015 8:49 AM
  • Did you change the path to the location of your log file? I created a test one on my C drive and pasted in the contents of your sample, it seemed to work pretty well - 

    PS C:\powershell> $pattern = "([0-9]{1,3}\.){3}[0-9]{1,3}"
    $ips = @()
    gc  C:\dns.log | % {
    
    if (($_ -match $pattern)) {
    
    $ips += [regex]::Match($_, $pattern).Value
    
    }
    
    }
    $ips
    10.10.30.21

    • Marked as answer by mjksgea Thursday, April 16, 2015 10:01 AM
    Thursday, April 16, 2015 9:48 AM
  • Hi

    no I did not but there were some headers at the top of the original file, remove it and it worked fine.

    I change the variable $pattern = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" which gave me cleaner output.

    many thanksfor your help

    mjksgea

    Thursday, April 16, 2015 10:01 AM