2

I got this code, which returns number of bytes:

$size = Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum

This works fine, but is not very user friendly, so I want to convert to megabytes or gigabytes.

After googling and looking at examples, I've tried this:

$size = "{0:N2}" -f ((Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum).Sum / 1MB)

However, PowerShell returns nothing.

Any idea why?

Edit: Posting complete code.

Function:

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
}
}

Script to generate report based on an input list of user IDs:

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}
Erik M.
  • 61
  • 7

1 Answers1

1

You can perform math operations on your first example:

$size = (Get-ChildItem $userAccount.homeDirectory -Recurse | Measure-Object -Property Length -Sum) / 1MB # or / 1GB

PowerShell has constants that define bytes.

If you want it to be a string, you can use a string subexpression:

$size = "$((GCI $userAccount.homeDirectory -Recurse | Measure Length -Sum) / 1MB)MB"
Maximilian Burszley
  • 15,132
  • 3
  • 27
  • 49