【问题标题】:Reduce output from three commands to one line将三个命令的输出减少到一行
【发布时间】:2016-12-04 17:04:30
【问题描述】:

我有这个脚本:

$counterWS = "\Process(powershell)\Working Set"
$counterWSPe = "\Process(powershell)\Working Set Peak" 
$counterWSPr = "\Process(powershell)\Working Set - Private"

$dataWS = Get-Counter -Counter $counterWS
$dataWSPe = Get-Counter -Counter $counterWSPe
$dataWSPr = Get-Counter -Counter $counterWSPr

$dataWS.countersamples | Format-Table Timestamp,@{Name='WorkingSet';Expression={($_.CookedValue/1KB)}},WorkingSetPeak,WorkingSetPrivate -Auto | findstr Timestamp
$dataWS.countersamples | Format-Table Timestamp,@{Name='WorkingSet';Expression={($_.CookedValue/1KB)}},WorkingSetPeak,WorkingSetPrivate -Auto | findstr [-]

while ($true) {
    $dataWS.countersamples | Format-Table Timestamp,@{Name='WorkingSet';Expression={($_.CookedValue/1KB)}},WorkingSetPeak,WorkingSetPrivate -Auto | findstr [:]
    $dataWSPe.countersamples | Format-Table Timestamp,WorkingSet,@{Name='WorkingSetPeak';Expression={($_.CookedValue/1KB)}},WorkingSetPrivate -Auto | findstr [:]
    $dataWSPr.countersamples | Format-Table Timestamp,WorkingSet,WorkingSetPeak,@{Name='WorkingSetPrivate';Expression={($_.CookedValue/1KB)}} -Auto | findstr [:]
    Start-Sleep -s $args[0]
}

结果是这样的:

时间戳 WorkingSet WorkingSetPeak WorkingSetPrivate
--------- ---------- -------------- -----
29/07/2016 18:41:12 10644
29/07/2016 18:41:13 10676
29/07/2016 18:41:14 3056

有没有办法减少这样的输出:

时间戳 WorkingSet WorkingSetPeak WorkingSetPrivate
--------- ---------- -------------- -----
29/07/2016 18:41:12 10644 10676 3056

【问题讨论】:

    标签: powershell output line


    【解决方案1】:

    一次收集所有 3 个计数器(参数 -Counter 接受参数列表),然后将结果拆分为单独的 calculated properties

    $ws     = '\Process(powershell)\Working Set'
    $wsPeak = '\Process(powershell)\Working Set Peak'
    $wsPriv = '\Process(powershell)\Working Set - Private'
    
    Get-Counter -Counter $ws, $wsPeak, $wsPriv |
        Select-Object Timestamp,
            @{n='WorkingSet';e={$_.CounterSamples[0].CookedValue / 1KB}},
            @{n='WorkingSetPeak';e={$_.CounterSamples[1].CookedValue / 1KB}},
            @{n='WorkingSetPrivate';e={$_.CounterSamples[2].CookedValue / 1KB}}
    

    CounterSamples 属性是PerformanceCounterSample 对象的列表,可以通过索引单独访问。

    如果您不想依赖按传递给Get-Counter 的参数的顺序返回的结果,您可以通过它们的路径选择它们,例如像这样:

    @{n='WorkingSetPeak';e={
      ($_.CounterSamples | Where-Object { $_.Path -like '*peak' }).CookedValue / 1KB
    }}
    

    对于连续样本采集,将参数-Continuous-SampleInterval 添加到Get-Counter。不需要循环。

    $interval = 5  # seconds
    
    Get-Counter -Counter $ws, $wsPeak, $wsPriv -Continuous -SampleInterval $interval |
        Select-Object ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2013-11-08
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多