在PowerShell中连接数组类似于连接DataFrame列

问题描述 投票:0回答:1

有没有办法在PowerShell中连接数组,类似于在Python Pandas中使用concat连接DataFrame列,或者在使用cbind连接R而不是遍历每个项目?

下面是一个可重现的示例,它将四个数组绑定在一起,作为PowerShell对象中的四列。我如何摆脱for循环并获得相同的结果?

$LogicalProcessors = (Get-WmiObject –class Win32_processor 
    -Property NumberOfLogicalProcessors).NumberOfLogicalProcessors;

function myTop([String]$SortCol='CPU', [Int32]$top=30) {
    $NameArray = get-counter '\Process(*)\ID Process' -EA SilentlyContinue | 
        Select -Expand CounterSamples | Select InstanceName, CookedValue
    $CpuArray = get-counter '\Process(*)\% Processor Time' -EA SilentlyContinue | 
        Select -Expand CounterSamples | Select CookedValue
    $MemArray = get-counter '\Process(*)\Working Set - Private' -EA SilentlyContinue | 
        Select -Expand CounterSamples | Select CookedValue

    $TopTable = For ($i=0; $i -lt $NameArray.Length; $i++) {
            if ($NameArray[$i].InstanceName -eq '_total') {continue}
            if ($NameArray[$i].InstanceName -eq 'memory compression') {continue}
            if ($NameArray[$i].InstanceName -eq 'idle') {
                $CPU = ($CpuArray[$i].CookedValue) / $LogicalProcessors;
            } else {
                $CPU = $CpuArray[$i].CookedValue;
            }
            [PSCustomObject]@{
                Name = $NameArray[$i].InstanceName;
                ID = $NameArray[$i].CookedValue;
                CPU = $CPU;
                Memory = $MemArray[$i].CookedValue;
            }
    }

    $TopTable | sort -des $SortCol | select -f $top |`
    select Name, ID,`
        @{Name='CPU'; Expression = {("{0:N1}%" -f $_.CPU) } },`
        @{Name='Memory'; Expression = {("{0:N0} K" -f ($_.Memory /1kb) )} }
}

myTop -SortCol Memory -top 30 | ft -a
powershell optimization vectorization
1个回答
1
投票

我认为PowerShell没有提供组合列的方法。在这种情况下,它可以通过Group-Object对应。

function myTop([string]$SortCol = "CPU", [int]$Top = 30)
{
    $LogicalProcessors = (Get-WmiObject Win32_processor NumberOfLogicalProcessors).NumberOfLogicalProcessors

    Get-Counter '\Process(*)\ID Process','\Process(*)\% Processor Time','\Process(*)\Working Set - Private' -ea SilentlyContinue |
    foreach CounterSamples |
    where InstanceName -notin "_total","memory compression" |
    group { $_.Path.Split("\\")[3] } |
    foreach {
        [pscustomobject]@{
            Name = $_.Group[0].InstanceName
            ID = $_.Group[0].CookedValue
            CPU = if($_.Name -eq "idle") { $_.Group[1].CookedValue / $LogicalProcessors } else { $_.Group[1].CookedValue } 
            Memory = $_.Group[2].CookedValue / 1KB
        }
    } |
    sort -des $SortCol |
    select -f $Top @(
        "Name","ID"
        @{ n = "CPU"; e = { ("{0:N1}%" -f $_.CPU) } }
        @{ n = "Memory"; e = { ("{0:N0} K" -f $_.Memory) } }
    )
}

myTop -SortCol Memory -top 10 | ft -a
© www.soinside.com 2019 - 2024. All rights reserved.