简体   繁体   中英

Get count from Powershell Group-Object

I am trying to get some stats about our code. This works fine for one module:

function countTestCases($path=$pwd) {
   Get-ChildItem $path -Recurse -Include *.java | Where-Object {-not $_.PSIsContainer } |     Select-String "extends ComponentTestCase", "extends DatabaseDependentTestcase" | Group-Object Pattern | Select-Object Count
}

but I want run this across all modules to get a CSV output like this:

module,#ComponentTestCase,#DatabaseDependantTestCase
module1,20,30
module2,12,1

unfortunately, if I add

| Select-Obejct Count

it doesn't work (although Name does). not sure how to get around this without writing too much code...

It works (at least for me). Is it perhaps because this data is right aligned and you don't notice it on the far right side of your console? Also, rather than use select, you can pick off "just" the property value with a Foreach cmdlet eg:

Get-ChildItem $path -Recurse -Filter *.java | Where {!$_.PSIsContainer } |
 Select-String "extends ComponentTestCase","extends DatabaseDependentTestcase" | 
 Group-Object Pattern | Foreach {$_.Count}

Select-Object creates a whole new object to contain just the properties you selected from the incoming object so a lot of the time it is overkill. Also, I would recommend using the Filter parameter on Get-ChildItem over Include as Fiter is quite a bit faster.

I couldnt simpler find a way.. but this seems to works

Get-ChildItem $path -Recurse -Include *.cs | Select-String "int", "string" | Group-Object Pattern -AsHashTable | foreach {
    new-object psobject -Property @{
        int = $_['int'].Count;
        string = $_['string'].Count;
        module = 'mymodulename'}
    } | select module, int, string

The output looks like

module                                            int                    string
------                                            ---                    ------
mymodulename                                       19                        78

I'm using string and int as my patterns, but you'll have to replace it for yours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM