This is a fairly simple idea, and one I’m sure many people have done in the past. Personally, I have tended to just hover a mouse over a folder when I want a size. That seems to work fairly well, but not only is it slow, it’s not programmatic.
I saw Jose Barreto write a quick OneDrive size script in PowerShell (PoSh), and thought it was interesting. It didn’t work for me as I’ve moved the OneDrive folder to my D: drive, so I had to alter this to get information. However in doing so, I decided to play with a function.
Here’s the code I used, altering Jose’s slightly.
UPDATE: Thanks to Mike Fal, one of my go-to PoSh experts, I’ve removed the aliases for Dir and %.
function Get-FolderInfo($folder) {
$OneDrives = $folder
Get-ChildItem $OneDrives | ForEach-Object {
$Files=0
$Bytes=0
$OneDrive = $_
Get-ChildItem $OneDrive -Recurse -File -Force | ForEach-Object {
$Files++
$Bytes += $_.Length
}
$Folders = (Get-ChildItem $OneDrive -Recurse -Directory -Force).Count
$GB = [System.Math]::Round($Bytes/1GB,2)
Write-Host “Folder ‘$OneDrive’ has $Folders folders, $Files files, $Bytes bytes ($GB GB)”
}
}
Note that I’ve passed in the folder name and then kept Jose’s code. This worked fine for me, as you can see below.
The next step for me was to make this programmatic and useful. All that text isn’t helpful. What I really want is just a size. I guess I need a folder name as well, so I built a function to return that information. I merely changed the last line to:
Write-Host “$GB”
I also moved this to the end of the function, rather than for each subfolder. With this change, I can now call this for a folder and get the size in GB returned.
And this checks out from Windows
I know there are better ways to write this function, but this was more of a programming exercise. This was really a 10 minute chance to practice and experiment a bit with PoSh and work on skills.
BTW, I used dot sourcing to load this as a function I could call
Filed under: Blog Tagged: powershell, syndicated