【问题标题】:Trying to store the output of a cmdlet to a variable尝试将 cmdlet 的输出存储到变量中
【发布时间】:2013-07-08 15:22:49
【问题描述】:

我正在尝试读取日志文件的最后一行并将其解析为特定的信息。日志文件是 .csv,我需要第三个字段中的数字。

while (1)
{ 
  Get-Content -Path C:\Users\alk6842\Desktop\logss.txt -Tail 1 -Wait | Foreach {($_ -split ',',4)[2]} | Foreach {($_ -split ' ',3)[1]}
}

这可以将其输出到屏幕上,但是我想将数字存储在变量中或作为数组中的元素,以便我可以使用它。我试过做

while (1)
{ 
  $a = Get-Content -Path C:\Users\alk6842\Desktop\logss.txt -Tail 1 -Wait | Foreach {($_ -split ',',4)[2]} | Foreach {($_ -split ' ',3)[1]}
  $a
}

但这不会输出任何东西。

谢谢。

【问题讨论】:

  • 我怀疑有些东西仍在写信给logss.txt,所以Get-Content 永远不会完成,因此脚本永远不会继续回显$a

标签: windows powershell scripting powershell-3.0


【解决方案1】:

您为什么使用-Tail 1 -Wait 选项?这意味着管道永远不会完成,如果管道没有完成,它将永远分配一些东西给$a

如果您想处理它并使用-Wait,请在Foreach-object 块内处理:

Get-Content -Path C:\Users\alk6842\Desktop\logss.txt -Tail 1 -Wait | 
ForEach-Object {
    $first = ($_ -split ',',4)[2];
    $second = ($_ -split ' ',3)[1]
    #do whatever processing you want
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2018-01-27
    • 2023-02-13
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多