I'm trying to make a Powershell function that takes in a piped string (from ExpandProperty).
for some reason I keep getting a null error (attached below), but if I run the code without the last piped command it works fine. I tried wrapping the Get-ChildItem pipeline in an array (@) too, but that didn't help.
error code
Get-FolderSize : Cannot bind argument to parameter 'folderpath' because it is null.
At line:31 char:106
+ ... ainer } | Select-Object -ExpandProperty FullName | Get-FolderSize $_
+ ~~
+ CategoryInfo : InvalidData: (:) [Get-FolderSize], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Get-FolderSize
code
$dirpath = "C:\SomeFolder"
Function Get-FolderSize {
# allows cmd options
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true, Position=0)]
$folderpath = $(Throw "no folder name specified")
)
if ($foldepath -eq $null){
return 0
}
$folderpath = Convert-Path {$folderpath}
$size = 0
# calculate folder size and recurse as needed
Foreach ($file in $(ls $folderpath -recurse)){
If (-not ($file.psiscontainer)) {
$size += $file.length
}
}
# return the value and go back to caller
return $size
}
$Files = @(gci $dirpath -Recurse | ?{ $_.PSIsContainer } | Select-Object -ExpandProperty FullName)
if ($Files.length -eq 0) {
write-host " no files to delete."
} else {
$Files
}
PSIsContainer, i.e.ls $folderpath -file -recurseandgci $dirpath -File -Recurse, unless your script needs to run on a PowerShell version before v3.0.