0

I have script that outputs a log file, now I need to read this log file and create a new log file for when it finds the words WARNING & ERROR and i need it to write the line number and output an error code from 0-20 for ERROR and 21-40 for WARNING, but everytime I rn the script my ExitCodeLog.lg is empty.

$file =  'H:\REPO\ADNEW\Testlog.log'#@(Get-ChildItem -Filter Remove-StallUserObjects_*.log)[-1]
$lineNumber = 0
$errorCode = 0
$warningCode = 21
$output = ForEach ($line in $file) {
    $lineNumber++
    if ($errorCode -eq 20) {
        $errorCode = 0
    }
    if ($warningCode -eq 40) {
        $warningCode = 21
    }
    if ($line -cmatch " ERROR: ") {
        "$lineNumber $errorCode"
        $errorCode++

    }
    if ($line -cmatch " WARNING: ") {
        "$lineNumber $warningCode"
        $warningCode++

    }
}
$output | Out-File -FilePath 'H:\REPO\ADNEW\ExitCodeLog.log'
Brad
  • 33
  • 6
  • Did you try to print only the value of `$line` with `Out-Host`? Why should the loop iterate a file name? 'H:\REPO\...' is a string not a file content. – harper Mar 20 '19 at 20:09

1 Answers1

1

The first problem is, that the contents of $file is a plain string.

You should use

$file = get-content 'H:\REPO\ADNEW\Testlog.log'

Furthermore you can optimize the first two if statements by using a modulo operator:

$errorcode = $errorcode % 20
$warningcode = 21 + ($warningcode % 20)
Peter Schneider
  • 2,879
  • 1
  • 14
  • 17
  • Thank you, silly me i forgot get-content, now it works, also i dont want to use the modulo operator as im new to this and i don't know exactly what its doing. – Brad Mar 20 '19 at 20:21
  • No problem. Modulo is the remainder of a division. So 10 % 3 = 1 because 10/3 = 3 remaining 1. See also [here](https://stackoverflow.com/questions/2664301/how-does-modulus-divison-work) for an explanation... ;-) – Peter Schneider Mar 20 '19 at 20:25