How do I get the number of distinct files in a directory in powershell?

▼魔方 西西 提交于 2020-01-03 18:01:04

问题


I currently have this code which returns the total number of files but I don't want to count multiple files in this number count?

Lets 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 count of 3 based on 01,02,05 but with my code I get 5.

How can I get it to return 3 and ignore everything past the first 2 characters in the string?


回答1:


I might suggest Group-Object:

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

Add | Measure-Object to count the number of groupings (this would be 3 in your example).




回答2:


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


来源:https://stackoverflow.com/questions/44504720/how-do-i-get-the-number-of-distinct-files-in-a-directory-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!