datetime - 如何向 PowerShell 和输出的各行添加时间戳?

标签 datetime powershell logging process

如何(如果有的话)向 & PowerShell 运算符生成的输出的每一行添加时间戳?

示例:

PS H:\> $result = & ping 192.168.1.1
PS H:\> echo $result

Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=104ms TTL=250
Reply from 192.168.1.1: bytes=32 time=106ms TTL=250
Reply from 192.168.1.1: bytes=32 time=102ms TTL=250
Reply from 192.168.1.1: bytes=32 time=102ms TTL=250
Ping statistics for 192.168.1.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 102ms, Maximum = 106ms, Average = 103ms

期望的结果:

PS H:\> echo $result

2014-12-08T14:45:48.8898125+00:00:Pinging 192.168.1.1 with 32 bytes of data:
2014-12-08T14:45:48.8932661+00:00:Reply from 192.168.1.1: bytes=32 time=104ms TTL=250
2014-12-08T14:45:48.9233451+00:00:Reply from 192.168.1.1: bytes=32 time=106ms TTL=250
2014-12-08T14:45:48.9765438+00:00:Reply from 192.168.1.1: bytes=32 time=102ms TTL=250
2014-12-08T14:45:49.0233105+00:00:Reply from 192.168.1.1: bytes=32 time=102ms TTL=250
2014-12-08T14:45:49.0233201+00:00:
2014-12-08T14:45:49.0238753+00:00:Ping statistics for 192.168.1.1:
2014-12-08T14:45:49.0239210+00:00:    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
2014-12-08T14:45:49.0233318+00:00:Approximate round trip times in milli-seconds:
2014-12-08T14:45:49.0237209+00:00:    Minimum = 102ms, Maximum = 106ms, Average = 103ms

我知道如何拆分/加入 PowerShell 数组,但这只能在 & 运算符完成后发生。我正在寻找更加实时的解决方案,其中在 & 运算符运行时将时间戳添加到输出中。

顺便说一句,时间戳本身是$($(Get-Date -Format o) + ":")

最佳答案

您可以使用过滤器:

filter timestamp {"$(Get-Date -Format o): $_"}
$result = & ping 192.168.1.1 | timestamp

$result 的示例输出:

2014-12-08T11:42:59.2827202-05:00: 
2014-12-08T11:42:59.2857205-05:00: Pinging 192.168.1.1 with 32 bytes of data:
2014-12-08T11:43:03.1241043-05:00: Request timed out.
2014-12-08T11:43:08.1236042-05:00: Request timed out.
2014-12-08T11:43:13.1241042-05:00: Request timed out.
2014-12-08T11:43:18.1246042-05:00: Request timed out.
2014-12-08T11:43:18.1246042-05:00: 
2014-12-08T11:43:18.1246042-05:00: Ping statistics for 192.168.1.1:
2014-12-08T11:43:18.1246042-05:00:     Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

关于datetime - 如何向 PowerShell 和输出的各行添加时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27361452/

相关文章:

r - 我如何绘制时间 (HH :MM:SS) in X axis in R

Python 日期时间提供错误的时区

c# - 日期对象与日期时间对象

powershell - Get-WinEvent 搜索所有错误

powershell - 在 powershell 脚本中管理来自外部命令的输入

c# - 如何在 Powershell 中模拟 Active Directory 用户?

logging - 使用ssl时如何获取haproxy详细的http日志?

php - 离任何日期还有多少天?

php - 产卵和监控过程的最佳方式?

visual-studio-2010 - VS2010 构建日志文件不正确