本文介绍了在PowerShell中联接数组,类似于串联DataFrame列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以在PowerShell中联接数组,类似于在Python Pandas中将DataFrame列与concat或在R中与cbind串联,而不是遍历每个项目?
Is there a way to join arrays in PowerShell similar to concatenating DataFrame columns in Python Pandas with concat or in R with cbind rather than iterating through every item?
下面是一个可重现的示例,该示例将四个数组作为PowerShell对象中的四列绑定在一起.如何摆脱for循环并获得相同的结果?
Below is a reproducible example that binds four arrays together as four columns in a PowerShell object. How would I get rid of the for loop and get the same results?
$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无法提供组合列的方法.在这种情况下,它可以对应Group-Object.
I think PowerShell doesn't provide a way to combine columns. In this case, it can correspond by 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更多推荐
在PowerShell中联接数组,类似于串联DataFrame列
发布评论