English 中文(简体)
假设在权力变量中出现价值
原标题:count the occurrence of a value in a variable in powershell

I have a simple for loop in powershell to loop through a json response

foreach ($myvar in $response) { 
    $getvalues = $myvar.acc_name
    Write-Host $getvalues
}

产出如下:

abc
abc
www
abc
bbb
abc

我需要增加代码,以计算变数和显示产出的发生情况如下:

abc 4
www 1
bbb 1
问题回答

Use the Group-Object cmdlet to group the values together - the resulting output will reflect the count of each distinct group:

PS ~> $strings = -split  abc abc www abc bbb abc 
PS ~> $strings |Group-Object -NoElement

Count Name
----- ----
    4 abc
    1 bbb
    1 www

Group-Object还接受比较的计算值:

PS ~> $strings = -split  abc abc www abc bbb abc 
PS ~> $strings |Group-Object {$_[1] <# group only on second letter in each string#> } -NoElement

Count Name
----- ----
    5 b
    1 w

如果投入如此的话:

$test = "abc
abc
www
abc
bbb
abc"

你们可以分开:

$lines = $test -split "`n"

在分类之后:

$groupedLines = $lines | ForEach-Object { $_.Trim() } | Group-Object | ForEach-Object {
[PSCustomObject]@{
    Count = $_.Count
    Value = $_.Name
    }
}

产出:

Count Value
----- -----
4 abc
1 bbb
1 www

如果没有<代码>ForEach-Object{_$_Trim() },你将获得这一产出:

Count Value
----- -----
1 abc
3 abc…
1 bbb…
1 www…

或许,我克服了这一问题:D





相关问题
wpf-DragDrop in a listbox with groupstyle

I am using the control library from http://code.google.com/p/gong-wpf-dragdrop/successfully for my listbox dragging operation.But there is an issue when i drop an item to a listbox with a group style....

Combine pairs to groups [PHP / Arrays]

I have pairs of items in an PHP array. Example: <?php $elements = array( tiger => lion , car => bike , lion => zoo , truck => plane ); ?> Now I want to combine ...

LINQ Merging results in rows

I have a LINQ query which returns a set of rows. The structure is: NAME, col1, col2, col3, col4 name1 1 null null null name1 null 1 null null name1 null null 1 1 As a ...

How to group items by date range in XSLT?

I have a bunch of data that looks a little like this: <item> <colour>Red</colour> <date_created>2009-10-10 12:01:55</date_created> <date_sold>2009-10-20 22:...

Self-Joins, Cross-Joins and Grouping

I ve got a table of temperature samples over time from several sources and I want to find the minimum, maximum, and average temperatures across all sources at set time intervals. At first glance this ...

Grouping with SubSonic 3

I have the following table "GroupPriority": Id Group Priority 1 1 0 2 2 0 3 3 0 4 2 1 5 1 1 6 2 2 7 ...

热门标签