Daniel
Daniel

Reputation: 113

Get total number of files and Sub folders in a folder

I have a task to carry out 3 times a day on a WS2012R2 to get the Disk size, total number of files and folders including subdirectories from a folder on a remote server.

Currently I get this information by RDP'ing to the target, navigating to the folder and right clicking the folder to copy the info:

enter image description here

I have already tried the PowerShell script :

Get-ChildItem E:\Data -Recurse -File | Measure-Object | %{$_.Count}

and other PowerShell scripts.

Which produced countless errors pertaining to not having permissions for some sub directories or simply gave results I didn't want such.

I have tried VBscript but VBscript simply cannot get this information.

Upvotes: 1

Views: 10798

Answers (2)

Andreas
Andreas

Reputation: 865

To summarise the comments so far.

You can get the size of the C drive with:

    $Drive = "C"
    Get-PSDrive -Name $Drive | Select-Object @{N="Used Space on $Drive Drive (GB)"; E={[Math]::Round($_.Used/1GB)}}

But you cannot use something like the code below to count the files & folders for the whole C drive, but it works for simple filestructures and simple drives. I use the code to calculate my other drives and for my homepath, just change $Path to e.g "$Env:Homepath".

There's the path length problem which is a .NET thing and won't be fixed until everyone (and PowerShell) is using .NET 4.6.2. Then there's that you're acting as you counting it, not the operating system counting.

[Int]$NumFolders = 0
[Int]$NumFiles = 0
$Path = "C:\"
$Objects  = Get-ChildItem $Path -Recurse

$Size = Get-ChildItem $Path -Recurse | Measure-Object -property length -sum
$NumFiles = ($Objects | Where { -not $_.PSIsContainer}).Count
$NumFolders = ($Objects | Where {$_.PSIsContainer}).Count

$Summary = New-Object PSCustomObject -Property @{"Path" = $Path ; "Files" = $NumFiles ; "Folders" = $NumFolders ; "Size in MB" = ([Math]::Round($Size.sum /1MB))}
$Summary | Format-list

To run this on remote computers, I would recommend using New-PsSession to the computer/computers, then Invoke-Command to run the code using the new sessions.

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 58931

You can just access the count property:

$items = Get-ChildItem E:\Data -Recurse -File
($items | Where { -not $_.PSIsContainer}).Count #files
($items | Where $_.PSIsContainer).Count #folders

Upvotes: 1

Related Questions