Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting output file?

I am extracting some errors from a log file into a separate file.

The errors that I am searching for are defined in a little block:

# Define all the error types that we need to search on
$error_6  = "Missing coded entry in table for provider sector category record"
$error_7  = "not a well-formed email address"
$error_8  = "Org Id must not contain invalid characters"
$error_9  = "Missing sub type code for provider type category record"
$error_10 = "Provider sub type"

I then read in the source log file and strip out the matching lines.

Weirdly, if I dump them into separate files I get the correct number of lines in each file, but if I use the same file I only get one line. I thought that it would append to the file.

This doesn't work (only one line of output):

(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_6 } |   Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_7 } | Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_8 } | Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_9 } | Set-Content $path\known_errors.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_10 } | Set-Content $path\known_errors.log

Works (16 lines of output in total):

(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_6 } | Set-Content $path\known_errors_6.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_7 } | Set-Content $path\known_errors_7.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_8 } | Set-Content $path\known_errors_8.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_9 } | Set-Content $path\known_errors_9.log
(Get-Content $path\temp_report.log) | Where-Object { $_ -match $error_10 } | Set-Content $path\known_errors_10.log
like image 338
zoomzoomvince Avatar asked Jul 16 '16 18:07

zoomzoomvince


2 Answers

Set-Content always creates a new file.

https://technet.microsoft.com/en-us/library/hh849828.aspx

Set-Content
Writes or replaces the content in an item with new content.

You need to use Add-Content to add data to an existing file.

https://technet.microsoft.com/en-us/library/hh849859.aspx

Add-Content
Adds content to the specified items, such as adding words to a file.

like image 100
Eris Avatar answered Nov 15 '22 05:11

Eris


Or you can use:

(Get-Content $path\temp_report.log) | Where-Object { $_ -match  $error_6 } |  out-file $path\known_errors.log -Append
like image 25
Esperento57 Avatar answered Nov 15 '22 05:11

Esperento57