0

次のコードを使用しています。

$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";

# 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
$num  = 0
$file = "$Folder\SQL_log_${num}.csv"
Get-Counter -counter $p -SampleInterval 2 -Continuous | 
    Foreach {
        if ((Get-Item $file).Length -gt 1MB) {
            $num +=1;$file = "$Folder\SQL_log_${num}.csv"
        }
        $_
    } | 
    Export-Counter $file -Force -FileFormat CSV
}
Else
{
$num  = 0
$file = "$Folder\SQL_log_${num}.csv"
Get-Counter -counter $p -SampleInterval 2 -Continuous | 
    Foreach {
        if ((Get-Item $file).Length -gt 1MB) {
            $num +=1;$file = "$Folder\SQL_log_${num}.csv"
        }
        $_
    } | 
    Export-Counter $file -Force -FileFormat CSV
}

ただし、((Get-Item $file).Length -gt 1MB)isTRUEの場合でも、ファイルをインクリメントしません。私の考えではForeach、サンプルが取得されるたびにループが呼び出されるわけではありません。これは、Get-Counter が 1 回だけ呼び出されている (そして進行中) ためです。そのループを通過していることを確認するためにどの構造を使用する必要があるかわかりません。Foreach実行中に呼び出されることに依存するのではなく、その特定のステートメントを別のセクションに分離する必要がありget-counterますか? この Powershell スクリプトはバッチ ファイルによって呼び出され、そのget-counter部分がバックグラウンドで実行され、情報が収集されます。

4

1 に答える 1

1

問題は、 on の $file 変数が実行Export-Counter時に 1 回しか評価されないことです。toExport-Counterの結果をパイプしてその中にエクスポートします ($file を強制的に再評価させます) が、これは各反復で出力ファイルを上書きし、残念ながらAppend スイッチがありません。Get-CounterForeach-ObjectExport-Counter

v3Export-Csvでは、ファイルへの追加をサポートしています。そうは言っても、同じ csv 構造は得られません。

あと2つ。スクリプトの最初の実行では、最初のファイルはまだ作成されていないため、その長さを確認します。これにより、ファイルが見つからないというエラーが発生します。エラーを抑制するには、ErrorAction パラメーターを使用します。

コードを 2 回繰り返す必要はありません。出力ディレクトリが存在するかどうかを確認し、存在しない場合は作成してから、残りのスクリプトを 1 回続行します。

$Folder = 'D:\temp'
$num  = 0
$file = "$Folder\SQL_log_${num}.csv"

if( !(test-path $folder)) {New-Item $Folder -type directory}

Get-Counter -counter $p -SampleInterval 2 -Continuous | Foreach {

    if ((Get-Item $file -ErrorAction SilentlyContinue ).Length -gt 1mb) 
    {
        $num +=1
        $file = "$Folder\SQL_log_${num}.csv"
    }

    $_

} | Foreach-Object { $_ | Export-Csv $file -Append} 
于 2013-05-29T19:48:16.157 に答える