Reputation: 351
I have to apply a command IF the folder size is greater or equal to 600MB.
I tried something like this
$folders = Get-ChildItem d:\home -exclude *.*
function Get-Size
{
param([string]$pth)
"{0:n2}" -f ((gci -path $pth -recurse | measure-object -property length -sum).sum /1mb)
}
ForEach ($subFolder in $folders){
echo $subFolder | select-object fullname
$size = Get-Size $subFolder
echo $size
if ($size -gt "600") { echo "Not ok." }
else { echo "OK template." }
}
It doesn't work. It writes the right size of the folder but the IF statement is not respected. How do I do?
Upvotes: 0
Views: 3835
Reputation: 200203
The simplest way is to use the FileSystemObject
COM object:
function Get-FolderSize($path) {
(New-Object -ComObject 'Scripting.FileSystemObject').GetFolder($path).Size
}
I'd recommend against doing formatting in a Get-Size
function, though. It's usually better to have the function return the raw size, and do calculations and formatting when you actually display the value.
Use it like this:
Get-ChildItem 'D:\home' | Where-Object {
$_.PSIsContainer -and
Get-FolderSize $_.FullName -gt 600MB
}
or like this:
Get-ChildItem 'D:\home' | Where-Object {
$_.PSIsContainer
} | ForEach-Object {
if (Get-FolderSize $_.FullName -gt 600MB) {
'Not OK.'
} else {
'OK template.'
}
}
On PowerShell v3 and newer you can use Get-ChildItem -Directory
instead of Get-ChildItem | Where-Object { $_.PSIsContainer }
.
Upvotes: 2
Reputation: 961
When you are comparing using $size -gt "600" the value is considered as string. Hence not getting right results.
Try comparison using integers.
Upvotes: 0