我得到了这段代码,它返回字节数:
$size = Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum
这样可以正常工作,但不是非常用户友好,所以我想转换为兆字节或千兆字节。
在使用Google搜索并查看示例后,我尝试过这样做:
$size = "{0:N2}" -f ((Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB)
但是,PowerShell不返回任何内容。
知道为什么吗?
编辑:发布完整代码。
功能:
Function Get-ADHomeDirectorySize
{
Param
(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
[Microsoft.ActiveDirectory.Management.ADUser]$User
)
Begin
{
$HomeD = @()
$size = $nul
}
Process
{
ForEach($userAccount in $User)
{
$userAccount = Get-ADUser $userAccount -properties homeDirectory
$size = "{0:N2}" -f ((Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB)
If($userAccount.homeDirectory -eq $nul)
{
Write-Host "`nERROR -- User: $userAccount has no Home Directory`n" -foregroundcolor red
Return
}
$obj = New-Object System.Object
$obj | add-member -type NoteProperty -name User -value $userAccount.Name
$obj | add-member -type NoteProperty -name HomeDirectory -value $userAccount.homeDirectory
$obj | add-member -type NoteProperty -name HomeDirectorySize -value $size.sum
$HomeD += $obj
}
}
End
{
$HomeD
}
}
根据用户ID的输入列表生成报告的脚本:
Get-Content brukerlistetest.txt | Foreach-Object {Get-ADUser $_ -properties homeDirectory | ? {$_.homeDirectory -ne $nul} | Get-ADHomeDirectorySize | sort HomeDirectorySize | Format-Table -HideTableHeaders | out-file output.txt -width 120 -append}
答案 0 :(得分:1)
您可以在第一个示例中执行数学运算:
$size = (Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum) / 1MB # or / 1GB
PowerShell具有定义字节的常量。
如果您希望它是一个字符串,您可以使用字符串子表达式:
$size = "$((GCI $userAccount.homeDirectory -Recurse | Measure Length -Sum) / 1MB)MB"