PSScriptTools icon indicating copy to clipboard operation
PSScriptTools copied to clipboard

Function "Get-FolderSizeInfo" can throw exception

Open Erikov-K opened this issue 3 years ago • 4 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! :-)

Erikov-K avatar Mar 28 '22 07:03 Erikov-K

I can see where this could be a problem with an empty folder. But I can't duplicate the problem.

image

What version of PowerShell and Windows (I assume) are you running?

jdhitsolutions avatar Mar 28 '22 13:03 jdhitsolutions

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))}
    }
}

image

Erikov-K avatar Mar 28 '22 14:03 Erikov-K

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.

jdhitsolutions avatar Mar 28 '22 15:03 jdhitsolutions

Added better handling of null values in this function in v2.43.0.

jdhitsolutions avatar Apr 04 '22 14:04 jdhitsolutions