0

I'm wondering how I can count a particular objects in the text file using PowerShell.

For example, this is the file I have:

Color: Black
Length: Long
Size: 30

Color: Blue
Length: Long
Size: 20

Color: Black
Length: Short
Size: 10

How do I "Color" that is "Black" ?

The output should be 2 according to the file.

3
  • 2
    Is this your file exactly? Or do you have a CSV? Make sure to provide exactly what your file looks like in order to receive an accurate answer. Commented Dec 22, 2020 at 23:06
  • Will the file always follow this set format? Commented Dec 22, 2020 at 23:58
  • Yes, this is the file exactly, and it will be in the same format. Thanks. Commented Dec 23, 2020 at 1:22

2 Answers 2

1

You can read the text as single multiline string and break it down into blocks on the empty line. Then do a simple regex to catch the string you want and get the Count property of the number of blocks that matched.

$colorToCount = 'Black'
((Get-Content -Path 'D:\Test\colors.txt' -Raw) -split '(\r?\n){2,}' | 
    Where-Object { $_ -match "(?m)^Color:\s*$colorToCount" }).Count

will return 2 using your example file.


If what you intend is to first create an array of objects from this text, you can do this:

# create an array of objects from the file
$data = (Get-Content -Path 'D:\Test\colors.txt' -Raw) -split '(\r?\n){2,}' | 
    Where-Object { $_ -match '\S' } | ForEach-Object {
        [PsCustomObject]($_ -replace ':', '=' | ConvertFrom-StringData)
    }

# now get the count of objects with the wanted color
$colorToCount = 'Black'

($data | Where-Object { $_.Color -eq $colorToCount }).Count
Sign up to request clarification or add additional context in comments.

Comments

0

I suppose your file is always same format :

#decomposition of your file into list of formated objects
$Objects=Get-Content "C:\temp\sample.txt" | where {$_ -ne ""} | %{

$Match=$_ -split "(?<Color>Color:.+)(?<Length>Length:.+)(?<Size>Size:.+)"

[pscustomobject]@{
Color=($Match[1] -split ": ")[1].trim()
Length=($Match[2] -split ": ")[1].trim()
Size=($Match[3] -split ": ")[1].trim()
}


} 

#Found object with color black
$Objects | where {$_.Color -eq 'Black'}

#Found number of object with color black
($Objects | where {$_.Color -eq 'Black'} | Measure-Object).Count

#you can use group too :)
$Objects | group Color

#you can use group too for found number of black ;)
($Objects | group Color | where Name -eq 'Black').Count

1 Comment

Thanks for the script, however I'm getting error at [pscustomobject]@{ line - "Unable to find type".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.