1

I'm trying to monitor a logs file latest entry and then pass the output to a variable so I can then do other stuff, for this example I'm just going to pop a message in the console.

$fail = Get-Content 'C:\ProgramData\Software\APP.LOG' -Tail 0 -Wait | Select-String 'Error Alert Entry'
if ($fail -contains 'Error Alert Entry'){Write-Host "Warning Will Robinson!"}

I've tested the Get-Content command on its own and this does Tail the output of the log file without issue but when set as Variable I do not get anything.

I've also tested the latter portion and this works when I manually define the $fail Variable using something like this:

$fail = 'Error Alert Entry'

It appears that the Variable does not like being populated by actively Tailing a log file. I would appreciate if someone could provide some guidance on how to overcome this issue.

1 Answer 1

1

Sometimes you have to check your assumptions with PS. Try this:

$fail

and then this:

$fail.GetType()

and now this:

$fail[0].GetType()

What you thought was an array of String is actually an array of MatchInfo returned by Select-String. You should be able to get what you want by digging the Value out of the MatchInfo objects:

$fail.matches.value -contains 'Error Alert Entry'

Or you can dig the value out in the first line:

$fail = (Get-Content 'C:\ProgramData\Software\APP.LOG' -Tail 0 -Wait | Select-String 'Error Alert Entry').Matches.Value

I have to admit, Get-Content -Tail 0 -Wait doesn't seem to work in my environment. That command seems to hang indefinitely despite making changes to the file.

/edit

Okay, I think I understand now. Get-Content -Tail 0 -Wait never exits, so it never finishes piping its output to Select-String and never allows $fail to receive the data.

One solution might be to wrap your Get-Content -Tail 0 -Wait in a job and loop a Receive-Job call to execute your Write-Host 'Warning Will Robinson!'

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.