Powershell写入控制台

时间:2014-08-27 19:03:42

标签: powershell console

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

    $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个错误

2 个答案:

答案 0 :(得分:4)

说实话,这很清楚......

$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行。

答案 1 :(得分:-2)

将行$ eText更改为以下内容并查看结果是否更改:

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

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