Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

How to Access and Store Windows User Profile Sizes with PowerShell

PowerShell has undeniably revolutionized the way IT professionals manage Windows systems, automate mundane tasks, and delve deeper into system diagnostics. Today, we delve into a PowerShell script designed to assess user profile sizes on Windows, a crucial tool for system administrators and Managed Service Providers (MSPs).

Background

With the rise of big data and increasingly sophisticated applications, managing storage and ensuring efficient disk utilization has become paramount. IT professionals and MSPs often grapple with challenges arising from users accumulating large amounts of data, sometimes unknowingly. This script addresses this concern by enabling IT professionals to swiftly determine user profile sizes, ensuring optimal storage management and system health.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Updates a Custom Field with the total size of all User Profiles.
    If the Max parameter is specified then it will return an exit code of 1
     for any profile being over that Max threshold in GB.
.DESCRIPTION
    Updates a Custom Field with the total size of all User Profiles.
    If the Max parameter is specified then it will return an exit code of 1
     for any profile being over that Max threshold in GB.
.EXAMPLE
     -Max 60
    Returns and exit code of 1 if any profile is over 60GB
.EXAMPLE
     -CustomField "Something"
    Specifies the name of the custom field to update.
.EXAMPLE
    No Parameter needed.
    Uses the default custom field name: TotalUsersProfileSize
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [Alias("MaxSize", "Size", "ms", "m", "s")]
    [Double]
    $Max,
    [Parameter()]
    [Alias("Custom", "Field", "cf", "c", "f")]
    [String]
    $CustomField = "TotalUsersProfileSize"
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
    function Format-FileSize {
        param($Length)
        switch ($Length) {
            { $_ / 1TB -gt 1 } { "$([Math]::Round(($_ / 1TB),2)) TB"; break }
            { $_ / 1GB -gt 1 } { "$([Math]::Round(($_ / 1GB),2)) GB"; break }
            { $_ / 1MB -gt 1 } { "$([Math]::Round(($_ / 1MB),2)) MB"; break }
            { $_ / 1KB -gt 1 } { "$([Math]::Round(($_ / 1KB),2)) KB"; break }
            Default { "$_ Bytes" }
        }
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    $Profiles = Get-ChildItem -Path "C:Users"
    $ProfileSizes = $Profiles | ForEach-Object {
        [PSCustomObject]@{
            Name   = $_.BaseName
            Length = Get-ChildItem -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Property Sum -ExpandProperty Sum
        }
    }
    $Largest = $ProfileSizes | Sort-Object -Property Length -Descending | Select-Object -First 1

    $Size = $ProfileSizes | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Property Sum -ExpandProperty Sum

    $FormattedSize = Format-FileSize -Length $Size

    $AllProfiles = $ProfileSizes | Sort-Object -Property Length -Descending | ForEach-Object {
        $FormattedSizeUser = Format-FileSize -Length $_.Length
        "$($_.Name) $($FormattedSizeUser)"
    }

    Write-Host "All Profiles - $FormattedSize, $($AllProfiles -join ', ')"

    Ninja-Property-Set -Name $CustomField -Value "$AllProfiles"

    if ($Max -and $Max -gt 0) {
        if ($Largest.Length -gt $Max * 1GB) {
            Write-Host "Found profile over the max size of $Max GB."
            Write-Host "$($Largest.Name) profile is $($Largest.Length / 1GB) GB"
            exit 1
        }
    }
    exit 0
}
end {}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script in question is segmented into the following sections:

  • Cmdlet Binding and Parameters: The script kicks off by defining parameters, such as Max which sets an optional threshold for profile size, and CustomField which specifies the name of the custom field to update.
  • Begin Section: Here, we have two utility functions:
    • Test-IsElevated: Checks if the script is run with administrator privileges.
    • Format-FileSize: Converts bytes into a readable file size format.
  • Process Section:
    • The script checks for administrator privileges.
    • It then fetches all user profiles from “C:Users” and calculates their sizes.
    • Profiles are sorted and the total size is computed.
    • Data is output to the host, and the ‘Ninja-Property-Set’ function updates the custom field.
    • If a Max parameter is specified, the script checks for profiles exceeding this size and exits with an appropriate code.

Potential Use Cases

Consider an MSP overseeing storage for a corporate client. The company suddenly faces storage constraints. Instead of opting for expensive storage upgrades, the MSP uses this script to identify any oversized user profiles. Armed with this data, they can then liaise with specific users or departments to manage and streamline storage better.

Comparison

Traditionally, getting cumulative sizes of Window user profiles required manual navigation through properties, third-party applications, or cumbersome scripts. This PowerShell script offers a streamlined approach, using native Windows functionalities to provide precise and actionable insights.

FAQs

  • Is Administrator privilege mandatory?
    Yes, the script requires administrator privileges to run.
  • What happens if a user profile exceeds the specified Max size?
    The script will output a message indicating which profile exceeds the size and will return an exit code of 1.
  • What’s the default custom field name if not specified?
    It’s “TotalUsersProfileSize”.

Implications

While this script is immensely beneficial, if not utilized correctly, it could raise privacy concerns. Extracting and potentially sharing user profile sizes might be viewed as invasive by some users. Additionally, for IT security, understanding user storage patterns can be a proactive way to detect unusual spikes in data, which might indicate malware or a potential data breach.

Recommendations

  • Always run diagnostic scripts during off-peak hours to avoid potential system lags.
  • Ensure you have obtained the necessary permissions and informed stakeholders before executing.
  • Regularly update and maintain the script to cater to changing system structures and requirements.

Final Thoughts

An IT management platform like NinjaOne can significantly augment this script’s utility, providing IT professionals with a more holistic view of system health, performance, and anomalies. Integrating such scripts within NinjaOne can offer real-time insights, making storage management an effortless task.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).