ChrisB
ChrisB

Reputation: 37

With PowerShell's Get-ChildItem, how to I list matching files AND count them at the same time

How do I show AND count matching files using a single Get-ChildItem command in PowerShell? Currently I am using two Get-ChildItem commands, the first to count, the second to display the files - works fine but it is not very effective when scanning an entire disk ...

Command to count the matches: $count = Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue | Measure-Object | %{$_.Count}

Command to display the files: Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue | %{$_.FullName}

Upvotes: 0

Views: 1743

Answers (3)

Esperento57
Esperento57

Reputation: 17492

Simply like this :

$AllFile=Get-ChildItem $searchLocation -File -Filter $filename -Recurse | select FullName
$AllFile.Count
$AllFile.FullName

Or you can ad a rank into your loop like this :

$Rang=0
Get-ChildItem "c:\temp" -File -Filter "*.txt" -Recurse | %{
$Rang++ 
Add-Member -InputObject $_ -Name "Rang" -MemberType NoteProperty -Value $rang 
$_
} | select Rang, FullName 

Upvotes: 1

Drew
Drew

Reputation: 4030

An alternative method is to add a file number to each file as it processes.

$i = 1
$Files = Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue
Foreach($Item in $Files) {
    $Item | Add-Member -MemberType NoteProperty -Name FileNo -Value $i
    $i++
}
$Files  | Select-Object FileNo, Fullname

You can then see the order the files were processed, get the last file number by doing $File[-1].FileNo. And it will maintain all the additional file metadata suck as CreationTime, DirectoryName, VersionInfo etc.

Upvotes: 1

vonPryz
vonPryz

Reputation: 24081

As Get-ChildItem is returning an array, its size is stored in .Length member and explicit measurement is not needed. Thus, store the file names in the same collection and then print length for number of entries and iterate the collection for file names. Swapping the variable name as $files to reflect this like so,

$files = Get-ChildItem -Path $searchLocation -Filter $filename `
  -Recurse -ErrorAction SilentlyContinue 
# ` can used to divide command into multiple lines (and work-around for markup stupidness)

# prints the number of items
$files.Length

# prints the full names
$files | %{$_.FullName}

Upvotes: 1

Related Questions