Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

Powershell: Count items in a folder with PowerShell

I'm trying to write a very simple PowerShell script to give me the total number of items (both files and folders) in a given folder (c:MyFolder). Here's what I've done:

Write-Host ( Get-ChildItem c:MyFolder ).Count;

The problem is, that if I have 1 or 0 items, the command does not work---it returns nothing.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use Measure-Object to count things. In this case it would look like:

Write-Host ( Get-ChildItem c:MyFolder | Measure-Object ).Count;

or if that's too long

Write-Host ( dir c:MyFolder | mo).Count;

and in PowerShell 4.0 use the measure alias instead of mo

Write-Host (dir c:MyFolder | measure).Count;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...