I cannot use a PowerShell Switch statement when 64 bits integers are involved.
I have the follwing PowerShell snippet :
PS D:\> cat .\dirSize.ps1
$dirName = $args[0]
$dirSize = [uint64]( ( dir "$dirName" -force -recurse | measure -property length -sum ).Sum )
switch( $dirSize ) {
{ $_ -in 1tb..1pb } { "{0:n2} TiB" -f ( $dirSize / 1tb ); break }
}
I get this error :
Cannot convert value "1099511627776" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
At C:\Users\sebastien.mansfeld\psh\dirSize.ps1:4 char:4
+ { $_ -in 1tb..1pb } { "{0:n2} TiB" -f ( $dirSize / 1tb ); break }
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastIConvertible
So I tried converting the switch test line to uint64 but it does not work :
switch( $dirSize ) {
{ [uint64]$_ -in [uint64]1tb..[uint64]1pb } { "{0:n2} TiB" -f ( $dirSize / 1tb ); break }
}
I get the same error message.
I'm expecting the switch condition to work.
Change your condition for something more efficient that wont throw that out of bounds error:
You could also make use of
PSTreeModule that comes with this built-in functionality, as an example, your current code would be replaced with:To install it, you can: