【问题标题】:Powershell write to consolePowershell 写入控制台
【发布时间】:2014-08-27 19:03:41
【问题描述】:

我正在尝试在控制台上写入错误数量和消息。我正在使用以下代码:

    $dir = "d:\logs\prov\"
    $latest = Get-ChildItem -PAth $dir | Sort-Object LastAccessTime -Descending |      Select-Object -First 1
    $eCounter = get-content $dir$latest | select-string "ERROR"
    $eCounter.Count
    $eText = "There are " + $eCounter.Count + " errors returned"

    if ($eCounter.count -gt 0)
    {
      $eCounter.Count
      $eText    
    }

正如代码所示,它会在文件夹中查找最新的日志文件,计算“ERROR”条目的数量,并将其与消息一起写入控制台。问题是结果是写了三行(如下)而不是两行。由于某种我无法弄清楚的原因,这个数字写了两次。我需要它写一次。

5

5

返回5个错误

【问题讨论】:

  • 也许我对 OP 太苛刻了,但我投了反对票,原因如下: 问题显示几乎没有努力。号码贴了 3 次,三个不同位置使用的唯一线路是什么? *.com/tour 很清楚,你不应该在没有展示你自己尝试过的情况下提问。在像这样的小(

标签: powershell console


【解决方案1】:

说实话很清楚......

$dir = "d:\logs\prov\"
$latest = Get-ChildItem -PAth $dir | Sort-Object LastAccessTime -Descending |      Select-Object -First 1
$eCounter = get-content $dir$latest | select-string "ERROR"

### LINE 1 (Number only)
$eCounter.Count

$eText = "There are " + $eCounter.Count + " errors returned"

if ($eCounter.count -gt 0)
{
### LINE 2 (Number only)
    $eCounter.Count
### LINE 3 (Full text)      
    $eText    
}

如果您只想要“返回有 ... 错误”这一行,则删除两个 $eCounter.count 行。

【讨论】:

    【解决方案2】:

    将$eText这一行改成如下,看看结果是否有变化:

    $eText = "There are " + [string]$eCounter.Count + " errors returned"
    

    问题是计数是一个整数,所以它不能正确地附加到字符串中

    【讨论】:

    • 嗯,好电话。反正我说的都是错的。为你点赞