You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PowerShell连通性测试脚本将时间戳写入日志文件?

PowerShell连通性测试脚本修复方案

问题场景

需要编写PowerShell脚本实现以下功能:

  • 测试指定IP/主机名列表的连通性
  • 设备无响应时,日志中需添加时间戳
  • 脚本持续运行2-3天
  • 当前问题:控制台能显示时间戳,但日志文件无时间戳且内容无换行,尝试手动添加换行符和嵌入时间戳未生效

修正后的脚本

# 配置文件路径与运行时长
$hostListPath = "C:\script\hname.txt"
$logPath = "C:\script\results.txt"
# 设置运行时长为3天(259200秒),可根据需求调整
$totalRunSeconds = 259200
$startTime = Get-Date

# 持续执行测试直到达到设定时长
while ((Get-Date) - $startTime -lt [TimeSpan]::FromSeconds($totalRunSeconds)) {
    # 每次循环重新读取主机列表,支持中途修改列表无需重启脚本
    $targetHosts = Get-Content $hostListPath
    
    foreach ($host in $targetHosts) {
        # 执行一次连通性测试
        if (Test-Connection -ComputerName $host -Count 1 -ErrorAction SilentlyContinue) {
            $logContent = "$host is up"
            Write-Host $logContent -ForegroundColor Green
            Add-Content -Path $logPath -Value $logContent
        }
        else {
            # 格式化时间戳,确保日志可读性
            $timeStamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            $logContent = "$timeStamp - $host is down"
            Write-Host $logContent -ForegroundColor Red
            Add-Content -Path $logPath -Value $logContent
        }
    }
    # 每轮测试间隔3秒
    Start-Sleep -Seconds 3
}

核心修改说明

  • 替换日志写入方式:放弃字符串拼接后用Out-File一次性写入的方式,改用Add-Content逐行追加,自动处理换行,无需手动添加\n\r
  • 嵌入时间戳到日志:将Get-Date格式化后直接拼接进down状态的日志字符串,确保日志文件中包含时间戳
  • 添加运行时长控制:通过外层while循环计算运行时间,自动在3天后停止脚本(可调整totalRunSeconds参数修改时长)
  • 动态读取主机列表:每次循环重新读取hname.txt,支持中途修改测试列表无需重启脚本
  • 控制台与日志同步:控制台输出和日志内容完全一致,便于实时排查问题

内容的提问来源于stack exchange,提问作者txjastx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:00:56