Out putting folder sizes to CSV with PowerShell

I wanted a way to track trends of some file shares on a server over time so I have written this powershell script to monitor them and put the data into a .csv file. This will also create the CSV file if it doesn’t exist already.

My plan is to pump the CSV into PowerBI and be able to monitor the growth trends of the folders and then use the data for planning.

Edit – 13/05/2020 – I have changed part of the script to stop an error I was having when I would run this on folders that are empty. It was resolved by adding the -File flag to the Get-ChildItem.

<#
.Author
Jake Gardner

.Notes
This will break if another folder is added. This still needs further developement so it doesn't break


.Version
1.0
1.1
- Added -File flag and $folder.fullname to the $folderSize, this makes it work when it is running on a different drive & also stops error that occurs when running on an empty folder by only measuring files.

#>

#Set the CSV file that you will be using to record the data
$loggingFile = 'shareStats.csv'
$loggingFilePath = 'C:\StatsFolder\'

$fullLoggingFile = $loggingFilePath + $loggingFile

#<----set the root folder of the folders you want to track - Just used xammp folder for testing. Change it ---->
$rootFolder = 'C:\xampp'

#<---Declare and set variables --->

$folders = Get-ChildItem $rootFolder -Directory
$allSizes = (get-date).ToString()
$allFolders = 'Date Time'


#this loop writes the folders and the folder sizes into the allSizes and allFolders arrays
foreach ($Folder in $folders)
{
$folderSize = "{0:N2}" -f ((Get-ChildItem $folder.FullName -Recurse -File | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)
$folderPath = $Folder.FullName

$allFolders = $allFolders + ',' + $folderPath
$allSizes = $allSizes + ',' + $folderSize
}


#<--- Check if the CSV file exists --->

$doesFileExist = Test-Path $fullLoggingFile

if ($doesFileExist -eq $false) {
$doesFilePathExist = Test-Path $loggingFilePath

    if ($doesFilePathExist -eq $false) {
    mkdir $loggingFilePath
    }

'SEP=,' >> "$fullLoggingFile"
$allFolders >> "$fullLoggingFile"

}

$allSizes >> "$fullLoggingFile"