【问题标题】:Batch Script : How to add timestamp before every line of log?批处理脚本:如何在每行日志之前添加时间戳?
【发布时间】:2021-07-08 20:17:27
【问题描述】:

我是批处理脚本的新手,我正在尝试创建一些可以使用 Tee-Object 看到终端输出和日志的东西。

这是工作代码:

powershell %* ^| tee-object -Append -FilePath "something.log"

但是,我希望在附加到日志文件之前添加时间戳,但找不到任何此类脚本。

这是 shell 脚本中的等效工作代码:

$* | while read line; do echo $line; echo "$(date) $line" >> something.log; done

【问题讨论】:

  • 我想我得问一下,如果你没有在你的SH 脚本中使用TEE,你为什么要尝试在PowerShell 中使用它。你不是在尝试做同样的事情。您的 SH 脚本正在执行两个 echo 命令。一个有日期,一个没有日期。
  • %* | foreach-object {$_;$(Get-Date).ToString() + ' ' + $_ | Out-File -append something.log}
  • 我可以为您提供一个纯批处理文件解决方案,但需要了解更多关于 %* 的值的上下文。

标签: powershell batch-file


【解决方案1】:

如果内容是文本行,可以添加时间戳:

%* ^| ForEach-Object { $(Get-Date).ToString() + ' ' + $_ } ^| Tee-Object ...

Tee-Object 与 UNIX/Linux 上的 tee 类似,旨在将相同的流发送到两个地方。不使用Tee-Object,可以写入两个不同的流。

if (Test-Path -Path '.\teetime.log') { Remove-Item -Path '.\teetime.log' }
@('now','is','the','time') |
    ForEach-Object {
        $(Get-Date).ToString() + ' ' + $_ |
            Out-File -FilePath '.\teetime.log' -Encoding ascii -Append
        Write-Host $_
    }

【讨论】:

  • 非常感谢。它可以工作,但我可以知道我是否只能将时间戳添加到日志文件而不是控制台?
  • @BipinKumarRachaputi, Tee-Objects 将相同的数据写入两个流。但是,您可以像第二个示例中所示单独编写。
  • @BipinKumarRachaputi,这能回答你的问题吗?
  • 是的,非常感谢您。但是我认为这对我有用:%* ^| ForEach-Object { 写主机 $_ ; $output_file =$(Get-Date).ToString() + ' ' + $_ ;写输出 $output_file ^| Out-File -FilePath something.log -Append -NoClobber}
  • @BipinKumarRachaputi,我很高兴你有一些工作。您的工作代码与我的第二个示例类似,但代码行数更少。
猜你喜欢
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 2014-08-22
  • 2015-08-30
  • 1970-01-01
相关资源
最近更新 更多