[英]How to compare a folder size in Powershell
如果文件夾大小大於或等於600MB,則必須應用命令。
我嘗試過這樣的事情
$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." }
}
沒用 它寫入正確的文件夾大小,但不遵守IF語句。 我該怎么辦?
最簡單的方法是使用FileSystemObject
COM對象:
function Get-FolderSize($path) {
(New-Object -ComObject 'Scripting.FileSystemObject').GetFolder($path).Size
}
不過,我建議不要在Get-Size
函數中進行格式化。 通常最好讓函數返回原始大小,並在實際顯示值時進行計算和格式化。
像這樣使用它:
Get-ChildItem 'D:\home' | Where-Object {
$_.PSIsContainer -and
Get-FolderSize $_.FullName -gt 600MB
}
或像這樣:
Get-ChildItem 'D:\home' | Where-Object {
$_.PSIsContainer
} | ForEach-Object {
if (Get-FolderSize $_.FullName -gt 600MB) {
'Not OK.'
} else {
'OK template.'
}
}
在PowerShell v3和更高版本上,可以使用Get-ChildItem -Directory
代替Get-ChildItem | Where-Object { $_.PSIsContainer }
Get-ChildItem | Where-Object { $_.PSIsContainer }
。
使用$ size -gt“ 600”進行比較時,該值被視為字符串。 因此沒有得到正確的結果。
嘗試使用整數進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.