0

I need help saving logs directly to a txt file. I made a simple monitoring script of our servers and computers. Basically I just need to know whether it is online or offline but i need the logs to be save directly whatever the output is.

While ($true) {
    $ServerName = Get-Content "E:\ServerList.txt"
    foreach ($Server in $ServerName) {
        if (test-Connection -ComputerName $Server -Count 3 -quiet ) {
            Write-Host "$Server is Online " -ForegroundColor Green ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss")
        } else {
            Write-Host "$Server - is Offline " -ForegroundColor Red ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss")
        }
    }

How can I improve it?

2
  • So what is the problem? How to write into a log file? Commented Feb 27, 2017 at 11:09
  • Yes i just want the output to save directly to txt file in realtime with date on it . basically whatever output displays saves into text file directly , like log file. could you pls help tnx Commented Feb 27, 2017 at 11:14

1 Answer 1

1

You can use Out-File cmdlet with -Append switch to save data in .txt file for logging.

In this example you will have both, info output to console and to file too:

$LogFile = 'C:\log.txt'
While ($true) {
    $ServerName = Get-Content "E:\ServerList.txt"
    foreach ($Server in $ServerName) {
        if (test-Connection -ComputerName $Server -Count 3 -quiet ) {
            Write-Host "$Server is Online " -ForegroundColor Green ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss")
            "{0}`t{1} is Online " -f (Get-Date).toString("yyyy/MM/dd HH:mm:ss"),$Server | Out-File $LogFile -Append -Force
        } else {
            Write-Host "$Server - is Offline " -ForegroundColor Red ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss")
            "{0}`t{1} is Offline " -f (Get-Date).toString("yyyy/MM/dd HH:mm:ss"),$Server | Out-File $LogFile -Append -Force
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

amazing , this is what im looking for. Could you please just explain me this line "{0}`t{1} ", im new to this powershell thingy and most i learn from here and from the help menu. xD
Place {0} {1} etc. into the string as placemarkers where you want the variables to appear, immediately follow the string with the -f operator and then lastly, a list of comma separated variables which will be used to populate the placemarkers. You can mark my answer as answer so it would help someone else with similar quiestion. :-)
Thanks Mr. Kirill Pashkov . Appreciate the help! :-)

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.