1

I have a text file log that looks like this

2 total number of add errors

I have a script that is

get-content "c:\logfile.txt | select-string "total number of add errors"

I cant remember how to get it to just show the number.

Any suggestions?

Matt
  • 45,022
  • 8
  • 78
  • 119
StrawDogz
  • 23
  • 1
  • 5

4 Answers4

1

You can use -match with a regular expression to parse the string:

get-content "C:\temp\test.txt" | select-string "total number of add errors" | Foreach{if ($_ -match "\d{1,5}") {$matches[0] }}

This will will pull out the number up to five digits. Change the second number in {1,5} if there will be larger numbers.

Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35
1

You don't need to "get-content" to feed into select-string, it can select straight from a file, but I think it works more neatly without using select-string at all so you can combine the test and getting the number:

gc logfile.txt |%{ if ($_ -match '^(\d+) total number of add errors') { $Matches[1] } }

And if you want to mostly avoid the regular expressions part, this shape works for string split as well:

gc logfile.txt | % { if ( $_ -match 'total number of add errors') { ($_ -split ' ')[0] } }
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0

Assuming that you will always have the line "x total number of add errors", you can set the result to a string and then trim it from there.

$newString = $firstString.Trim(" total number of add errors")

See link

Matt
  • 45,022
  • 8
  • 78
  • 119
0

This may be what you are looking for:

#Get the file contents
$text = (Get-Content c:\test.txt)

#If you want to get an error count for each line, store them in a variable 
$errorCount = ""

#Go thru each line and get the count
ForEach ($line In $text)
{
   #Append to your variable each count
  $errorCount = $errorCount + $line.Substring(0,$line.IndexOf("total")).Trim() + ","
}

#Trim off the last comma
$errorCount = $errorCount.TrimEnd(',')

#Pint out the results in the console
Write-Host "Error Counts: $errorCount"
Mike
  • 550
  • 2
  • 16