【问题标题】:Using a rolling log file within a Powershell script that gathers performance counters在收集性能计数器的 Powershell 脚本中使用滚动日志文件
【发布时间】:2013-05-28 23:26:53
【问题描述】:

好的,所以我有一个不错的 .ps1 脚本,它获取一组计数器并将其写入一个最大大小为 1GB 的循环日志文件。效果很好,让每个人都开心。

目前,它的触发方式是通过运行脚本的 .bat 文件,然后在隐藏窗口中保持 Powershell.exe 实例打开。这使它可以不显眼地运行。

但是,我真的不喜欢“循环”日志文件的想法。我正在获取大量信息,在其中一些服务器上,这意味着即使是 1GB 限制也会经常受到影响。我正在运行测试以查看实际需要多长时间,但可以预见滚动日志文件可能会更好。

我发现有一个函数可以检查特定文件的大小并在必要时创建一个新文件,但我不太确定如何定期调用该函数(例如,每天或每小时一次或一些东西)来自基本上是一劳永逸的Powershell脚本。

更复杂的是,我在这种情况下对 start-job 和 stop-job 的实验似乎效果不佳。它根本不会创建日志文件。

代码:

# This script tracks performance counters useful for tracking performance on a SQL server in a rolling .csv file 
located at a directory of your choosing. It is written for Powershell v.2

$Folder="C:\Perflogs\BBCRMLogs" # Change the bit in the quotation marks to whatever directory you want the log file 
# stored in

$Computer = $env:COMPUTERNAME
$1GBInBytes = 1GB
$p = LOTS OF COUNTERS GO HERE;

# If you want to change the performance counters, change the above list. However, these are the recommended counters for 
a client machine. 

$dir = test-path $Folder 

IF($dir -eq $False) 
{
New-Item $Folder -type directory
get-counter -counter $p -SampleInterval 60 -Continuous | Export-Counter  $Folder\SQL_log.csv -Force -FileFormat CSV 
-Circular -MaxSize $1GBInBytes
}
Else
{
get-counter -counter $p -SampleInterval 60 -Continuous | Export-Counter  $Folder\SQL_log.csv -Force -FileFormat CSV 
-Circular -MaxSize $1GBInBytes
}

敏锐的眼睛会注意到缺少滚动功能。这是因为上面的脚本是我的稳定版,我正在使用的功能在这里:

http://sysbrief.blogspot.com/2011/05/powershell-log-rotation-function.html

有什么想法吗?我不希望不必运行单独的 Powershell 实例来充当侦听器,或者让用户自己定期运行该函数,但我对任何想法都持开放态度。

设置一个 Windows 作业以定期在 powershell 中触发该功能并滚动日志文件会更好吗?

【问题讨论】:

    标签: logging powershell listener perfmon


    【解决方案1】:

    你应该能够处理这个内联例如:

    $num  = 0
    $file = "$Folder\SQL_log_${num}.csv"
    Get-Counter -counter $p -SampleInterval 60 -Continuous | 
        Foreach {
            if ((Get-Item $file).Length -gt 900MB) {
                $num +=1;$file = "$Folder\SQL_log_${num}.csv"
            }
            $_
        } | 
        Export-Counter $file -Force -FileFormat CSV -Circular -MaxSize $1GBInBytes
    

    这将持续测试文件大小,当达到限制时,它将更改日志文件的文件名。重要的是,该测试/重命名脚本都不输出任何内容。唯一应该沿管道输出的是由$_ 表示的性能计数器数据。

    【讨论】:

    • 这非常简单,而且很有意义。但是我仍然不太确定 $_ 在做什么。它只是某种占位符吗?
    • $_ 表示 Get-Counter 输出的对象。我们插入管道以检查文件大小,但我们需要确保 Get-Counter 输出的对象将其通过管道传递到 Export-Counter。
    • 啊,有道理。感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2018-09-06
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多