jdhitsolutions / PSScriptTools

:wrench: :hammer: A set of PowerShell functions you might use to enhance your own functions and scripts or to facilitate working in the console. Most should work in both Windows PowerShell and PowerShell 7, even cross-platform. Any operating system limitations should be handled on a per command basis. The Samples folder contains demonstration script files
MIT License
901 stars 112 forks source link

Function "Get-FolderSizeInfo" can throw exception #129

Closed Erikov-K closed 2 years ago

Erikov-K commented 2 years ago

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! :-)

jdhitsolutions commented 2 years ago

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?

Erikov-K commented 2 years ago

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

jdhitsolutions commented 2 years ago

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 commented 2 years ago

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