Question

When I'm Using below script...

$pattern = 'Unable to create Load Balance Manager object!'
$events = Get-WinEvent -ea SilentlyContinue `
-ProviderName "Hyperion Financial Data Quality Management - Task Manager Service"|
Where-Object { $_.TimeCreated -gt [datetime]::now.AddMinutes(-15) -and $_.Message -match $pattern }
$events |Export-Csv D:\Temp.txt  -Encoding Unicode -notype
[System.IO.File]::ReadAllText("D:\Temp.txt") | Out-File D:\Error.txt -Append -Encoding Unicode

I'm ended with getting a Temp.txt file with 1 KB size and a Error.txt file with INCREASING SIZE everyday but with NO CONTENT inside it.

I know this scripts works well as I've tested it but I'm not getting why in case of no specified pattern found it keeps increasing the size of Error.txt without any content added to it ?

Or is it adding blank lines on every run at 15 mins interval ? If this is the case how i can prevent this to happen. I just want to make sure that it should only add the content (in case of Error found) not the blank lines on every run which seems to be quite misleading.

Please suggest..!

Was it helpful?

Solution

ReadAllText() returns an empty string-object, and since you're using -Append with your Out-File cmdlet, the error.txt is updated with this emtpy-string + a linebreak(because of -Append) each time.

You can solve it by adding a check to test if the data from temp.txt is not null. That will remove the empty string-object from being pipelined to Out-File in the first place. Something like this:

[System.IO.File]::ReadAllText("D:\Temp.txt") | ? { $_ } | Out-File D:\Error.txt -Append -Encoding

or

[System.IO.File]::ReadAllText("D:\Temp.txt") | ? { $_ -ne "" } | Out-File D:\Error.txt -Append -Encoding
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top