我需要帮助将日志直接保存到 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")
} else {
Write-Host "$Server - is Offline " -ForegroundColor Red ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss")
}
}
我该如何改进它?
最佳答案
您可以使用 Out-File cmdlet 和 -Append 开关将数据保存在 .txt 文件中以进行记录。
在此示例中,您将同时将信息输出到控制台和文件:
$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
}
}
}
关于javascript - 如何在Powershell中将实时输出保存到txt文件?监控脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42484020/