Using PowerShell to get folder sizes

At work, I had to gauge how much impact turning off folder redirection would have for a customer. To do this you need to figure out how much data users have in their redirected folders, because the process will copy everything down to their local folder.

The structure of the folders was, “Username\Documents” with “Documents” being the redirected folder. So initially, I looped through each of the Username folders and grabbed the Length property of each. However, what I found was that a lot of them didn’t have a Length property for whatever reason.

To get round that, instead of getting the length property of the folder I used the GetFiles() method and then used the Measure-Object cmdlet to measure the length of the files. Using that, I was able to use -Sum and get the size of the folder.

(Get-Item "$user\Documents").GetFiles() | Measure -Sum -Property Length

By default it output the data in bytes, which isn’t easily read. So I formatted the data into MB and told it I only wanted the first 3 decimal points.

Select @{n="Size";e={$_.Sum / 1MB}} | Select -expand Size
$data = "$user"+","+("{0:N3}" -f $fs)

I wrote that to a variable and returned that to the Output stream, so I could write everything in the variable to a CSV file outside the loop. The finished script is below:

$u = Get-ChildItem | Select -expand Name
$rows = Foreach($user in $u){
if((Test-Path "$user\Documents")){
$fs = (Get-Item "$user\Documents").GetFiles() | Measure -Sum -Property Length | Select @{n="Size";e={$_.Sum / 1MB}} | Select -expand Size
$data = "$user"+","+("{0:N3}" -f $fs)
$data = "$user"+","+"N/A"
write $data
$rows | Out-File C:\temp\RFSize.csv

Using PowerShell to get folder sizes

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s