Home > Mobile >  Trying to get folder sizes for all users directory
Trying to get folder sizes for all users directory

Time:10-09

I am trying to write a powershell that will look at a network share and write out to a CSV the full name of the share and the size in MB or GB of those folders for each user home directory folder.

This is my code so far:

$StorageLocation = '\\wgsfs01\USERDIR\USERS'
$Roots = Get-ChildItem $StorageLocation | Select Fullname
ForEach ($Root in $Roots) { (Get-ChildItem $Root -Recurse | Measure-Object -Property Length -Sum).Sum }

I believe there is something wrong with my ForEach statement as this is my error message

Get-ChildItem : Cannot find path 'C:@{FullName=\wgsfs01\USERDIR\USERS' because it does not exist.

I appreciate any advice and thank you in advance.

CodePudding user response:

The issue you have is that FullName contains a DirectoryInfo object, you have two options;

  1. Change your select to ExpandProperty which will change it to a string of the full path.

    Select-Object -ExpandProperty Fullname

  2. Refer to $Root using the property FullName which is a property on the DirectoryInfo Object.

    Get-ChildItem -path $Root.FullName -Recurse

This is one solution to what you are trying to achieve, note that errors (e.g. access denied) are ignored.

Get-ChildItem $StorageLocation | ForEach-Object {

    $sizeInMB = (Get-ChildItem $_.FullName -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum / 1MB

    New-Object PSObject -Property @{
        FullName = $_.FullName
        SizeInMB = $sizeInMB
    }
}
  • Related