Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Size of User profiles with powershell

Tags:

powershell

I'm Trying to retrieve the exact size of the profile in windows machine.

below is my code and O/P

$profiles = Get-ChildItem C:\Users | ?{Test-path C:\Users\$_\NTUSER.DAT} | Select -ExpandProperty Name
  foreach($profile in $profiles)
    {
    $largeprofile = Get-ChildItem C:\Users\$profile  -recurse | Measure-Object -Sum length | Select -ExpandProperty Sum
    $largeprofile = [math]::Round(($largeprofile/1MB),2) + "MB"
    if($largeprofile -lt 20){Continue}
    $object = New-Object -TypeName PSObject
    $object | Add-Member -MemberType NoteProperty -Name Name -Value $profile
    $object | Add-Member -MemberType NoteProperty -Name "Size(MB)" -Value $largeprofile
    ($object | fl | Out-String).Trim();Write-Output "`n"
    }

O/P

Name : admin

Size(MB) : 34.62

however exact size of the folder is 181MB,powershell is not able to read all the folders and files inside the parent folder, how can I get the exact size which is displayed in a properties of the folder.

Note : For Folders other than the profile folder o/p is correct.

like image 257
Nirav sachora Avatar asked Jan 21 '26 08:01

Nirav sachora


1 Answers

You will have to add the parameter -Force to Get-ChildItem when you are Recursing the directory. From the docs Get-ChildItem the -Force parameter:

Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system files.

Additionally, you will want to add -ErrorAction SilentlyContinue so you don't get flooded with Access Denied errors. These changes makes your code look like this:

$profiles = Get-ChildItem C:\Users | ?{Test-path C:\Users\$_\NTUSER.DAT} | Select -ExpandProperty Name
  foreach($profile in $profiles)
    {
    $largeprofile = Get-ChildItem C:\Users\$profile -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Sum length | Select -ExpandProperty Sum
    $largeprofile = [math]::Round(($largeprofile/1MB),2) + "MB"
    if($largeprofile -lt 20){Continue}
    $object = New-Object -TypeName PSObject
    $object | Add-Member -MemberType NoteProperty -Name Name -Value $profile
    $object | Add-Member -MemberType NoteProperty -Name "Size(MB)" -Value $largeprofile
    ($object | fl | Out-String).Trim();Write-Output "`n"
    }
like image 134
HAL9256 Avatar answered Jan 24 '26 10:01

HAL9256



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!