繁体   English   中英

如何在Powershell中将实时输出保存到txt文件? 监控脚本

[英]How to save realtime output to txt file in Powershell ? Monitoring Script

我需要帮助将日志直接保存到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
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM