0

I have the following block in script that checks a log file and if it finds a specific line, should continue.

$keywords=Get-Content "C:\Users\user\desktop\keywords.txt"
Get-Content "C:\Users\user\desktop\some.log" -tail 1 -wait |
ForEach-object {
foreach($word in $keywords) {
if($_ -match "$word") {
Write-EventLog -LogName Application -EventID 2001 -EntryType Information -Source serviceCheck -Message "[SUCCESS] The service has been initialized"
Write-Host "[SUCCESS] The service has been initialized" 
}
}
} | Select -First 1

This logs the event but never continues with the rest of the script. If I put some other command in if($_ -match "$word") {get-date} for example or anything else, it works and continues to the next command.

How should this be made to write in event viewer and continue?

7
  • 1
    @SantiagoSquarzon It probably should, it's used to terminate Get-Content -Wait Commented Dec 28, 2022 at 12:53
  • It works for me. Every time I append a keyword to the log it runs write-eventlog. Commented Dec 28, 2022 at 13:40
  • @js2010 yes, it works, but doesnt continue with the execution. Commented Dec 28, 2022 at 14:27
  • That is the logic of your code. Until get-content stops running, the foreach-object loop will run forever. Commented Dec 28, 2022 at 14:34
  • Breaking out of a foreach-object loop is difficult. Commented Dec 28, 2022 at 15:09

1 Answer 1

2

You need to output something for the Select -First 1 statement to react to:

$keywords = Get-Content "C:\Users\user\desktop\keywords.txt"
Get-Content "C:\Users\user\desktop\some.log" -tail 1 -wait |ForEach-object {
    foreach ($word in $keywords) {
        if ($_ -match "$word") {
            Write-EventLog -LogName Application -EventID 2001 -EntryType Information -Source serviceCheck -Message "[SUCCESS] The service has been initialized"
            Write-Host "[SUCCESS] The service has been initialized" 
            "literally any value will do!"
        }
    }
} | Select -First 1 |Out-Null
Sign up to request clarification or add additional context in comments.

4 Comments

It doesnt work, I see your point but thats why you have write-host, just to popup something. As I said - with anything different than write-eventlog it works.
Oh I got it, there is a line "literally any value will do!" . It does break it and does not print anything. Awesome!
Oh, so you want to quit the foreach-object loop using "select -first 1", the first time you write an event log.
@Delyan Write-Host doesn't actually output to the pipeline, it writes straight to the host application (hence no effect) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.