user2075017
user2075017

Reputation: 477

Write-host output is not being redirected to logfile

I have written a powershell to find a pattern in log files and then redirect them to a log file. I wanted to have headers for each of the server and hence wrote the code as below:

But the header files are not redirected to the log file. Any suggestion please.

Code as mentioned below:

    $date_value=Get-Date -Format ddMMM 
    #$file_path="D:\Temp\Arun\mu.log"
    $file_path1="\\server1\d$\Temp\Arun\abc.log"
    $file_path2="\\server2\d$\Temp\Arun\abc.log"
    $file_path3="\\server3\d$\Temp\Arun\abc.log"
    # Set the match patterns in the three clusters
    $match_pattern1=select-string -pattern $date_value $file_path1
    $match_pattern2=select-string -pattern $date_value $file_path2
    $match_pattern3=select-string -pattern $date_value $file_path3
    $LogDir="D:\temp\arun\Log\"
    $DTS=Get-Date -Format "yyyy_MM_dd_HH_mm_ss"
    $LogFile = $LogDir+"fetch_data."+$DTS+".log"
    $OldLog = $LogFile+".old"
    Write-Host "**********************************************************" >> $LogFile
    Write-Host "Checking log for today's entries in SERVER1"  >> $LogFile
    Write-Host "**********************************************************" >> $LogFile
    $match_pattern1  >> $LogFile
    Write-Host "**********************************************************" >> $LogFile
    Write-Host "Checking log for today's entries in SERVER2" >> $LogFile
    Write-Host "**********************************************************" >> $LogFile
    $match_pattern2  >> $LogFile
    Write-Host "**********************************************************" >> $LogFile
    Write-Host "Checking log for today's entries in SERVER3" >> $LogFile
    Write-Host "**********************************************************" >> $LogFile
    $match_pattern3  >> $LogFile

I would also appreciate if anyone can help me in getting a code in addition to the above so that log file emailed as an attachment.

Upvotes: 0

Views: 2577

Answers (2)

jbockle
jbockle

Reputation: 643

Not liking this functionality I wrote a function to do this, The log message is set to still be visible through your console:

FUNCTION Write-Log ($message) {
Write-Host $message
$message | Out-File $LogFile -Append
}

Write-Log "..."

Upvotes: 4

Shay Levy
Shay Levy

Reputation: 126712

Write-Host writes to the console not to the pipeline. Check the Out-File and Add-Content cmdlets for adding content to files. See the help of Send-MailMessage cmdlet on how to send emails.

Upvotes: 4

Related Questions