How to get the number of individual files in a directory in powershell?

I currently have this code that returns the total number of files, but I do not want to count several files in this number?

Let's say I have this:

01Red.txt
01Blue.txt
02Red.txt
05Red.txt
05Green.txt

Get-ChildItem -File *.txt -Path "C:\Users\Test\Desktop\TestDirectory" | Measure-Object | %{$_.Count}

I want to return a total of 3 based on 01.02.05, but with my code I get 5.

How can I make it return 3 and ignore everything except the first 2 characters in the string?

+4
source share
2 answers

I could suggest Group-Object:

Get-ChildItem *.txt | Group-Object { $_.Name.Substring(0,2) }

Add | Measure-Objectto count the number of groupings (this will be 3 in your example).

+7
source
Get-ChildItem -File *.txt -Path "C:\Users\Test\Desktop\TestDirectory" 
| select {$_.BaseName.Substring(0,2)} | Get-Unique -AsString | measure
+5
source

Source: https://habr.com/ru/post/1679075/


All Articles