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?
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
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.