Powershell 如何让FOREACH语句在每次获得反火力时开火
我正在使用以下代码:Powershell 如何让FOREACH语句在每次获得反火力时开火,powershell,foreach,perfmon,Powershell,Foreach,Perfmon,我正在使用以下代码: $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 performanc
$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)
为TRUE
,它也不会使文件递增。我的想法是,Foreach
循环不会在每次采样期间被调用,因为Get计数器只被调用一次(然后正在进行)。我不确定应该使用什么构造来确保它通过该循环。我是否应该将特定的Foreach
语句隔离到另一个部分中,而不是依赖于在get counter
期间调用它?批处理文件正在调用此Powershell脚本,然后get counter
部分在后台运行,收集信息。问题是导出计数器上的$file变量在执行导出计数器时只计算一次。通过管道将Get Counter
的结果传输到Foreach对象
并在其中导出(强制$file重新求值),但这将在每次迭代中覆盖输出文件,不幸的是export Counter
没有附加开关
在我看来,您可以使用导出csv
导出到csv,在v3中,它支持附加到文件。也就是说,您将无法获得相同的csv结构
还有两件事。在脚本的第一次执行中,第一个文件尚未创建,然后检查其长度。如果给文件找不到错误,请使用ErrorAction参数抑制错误
您不需要重复代码两次。检查输出目录是否存在,如果不存在,则创建输出目录,然后使用脚本的其余部分继续一次
$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}
嘿,Shay,所以我测试了你的代码,一旦达到1MB,它确实会将日志文件滚动到一个新的日志文件中。。。不过,每次计数器触发后,它看起来都会创建一个新的1MB文件。所以几天后,我有200多个日志文件。有什么想法吗?我认为这可能与-Append开关有关。进一步研究后,可能是因为它想导出整个CSV。此外,它看起来将在内存中存储越来越多的内存(powershell以65MB的RAM结束)。