Function "Get-FolderSizeInfo" can throw exception
Erikov-K opened this issue · comments
Hello!
Firstly, Thank you for great function which calculate folder size using .NET.
It's work more than two times quickly on folders with millions of files.
I open issue, because function "Get-FolderSizeInfo" can throw exception at line 46 in code
if ($data.count -gt 1) {
, when $data
does not contains property "count".
This occurred in condition when folder is empty.
Exception: The property 'count' cannot be found on this object. Verify that the property exists.
I think, you can add this code before line 46 to solve issue
if (($data.psobject.members.name) -contains "count") {
Have a good day! :-)
I run this code on Windows 11 and Windows Server 2019, results were the same.
Set-StrictMode -Version 3.0
$psversiontable
$Path = 'C:\Temp\EmptyFolder'
Remove-Item -Path $Path
New-Item -type Directory -Path $Path
$cPath = (Convert-Path -literalpath $path -ErrorAction Stop)
if (Test-Path -literalpath $cPath -ErrorAction Stop) {
$d = [System.IO.DirectoryInfo]::new($cPath)
$files = [system.collections.arraylist]::new()
If ($psversiontable.psversion.major -gt 5) {
#this .NET class is not available in Windows PowerShell 5.1
$opt = [System.IO.EnumerationOptions]::new()
$opt.RecurseSubdirectories = $True
# https://docs.microsoft.com/en-us/dotnet/api/system.io.fileattributes?view=net-6.0
$opt.AttributesToSkip = "SparseFile", "ReparsePoint"
$data = $($d.GetFiles("*", $opt))
if ($data.count -gt 1) {$files.AddRange($data)}
elseif ($data.count -eq 1) {[void]($files.Add($data))}
}
}
It is Set-Strictmode
that is causing the exception. If you comment that line out you won't get an error. But, I can see where it might help to improve the code in the function.
Added better handling of null values in this function in v2.43.0.