{"id":208628,"date":"2024-01-31T18:07:35","date_gmt":"2024-01-31T18:07:35","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/tamano-de-los-perfiles-de-usuario\/"},"modified":"2024-03-04T19:21:08","modified_gmt":"2024-03-04T19:21:08","slug":"tamano-de-los-perfiles-de-usuario","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/tamano-de-los-perfiles-de-usuario\/","title":{"rendered":"C\u00f3mo conocer el tama\u00f1o de los perfiles de usuario de Windows y almacenarlos con PowerShell"},"content":{"rendered":"<p>Es innegable que PowerShell ha revolucionado la forma en que los profesionales de TI gestionan los sistemas Windows, automatizan tareas mundanas y profundizan en el diagn\u00f3stico de sistemas. Hoy nos adentramos en un script de PowerShell dise\u00f1ado para <strong>evaluar el tama\u00f1o de los perfiles de usuario en Windows<\/strong>, una herramienta crucial para los administradores de sistemas y los proveedores de servicios gestionados (MSP).<\/p>\n<h2>Antecedentes<\/h2>\n<p>Con el auge de los macrodatos y las aplicaciones cada vez m\u00e1s sofisticadas, gestionar el almacenamiento y garantizar una utilizaci\u00f3n eficiente de los discos se ha convertido en algo primordial. Los profesionales de TI y los MSP se enfrentan a menudo a retos derivados de la acumulaci\u00f3n de grandes cantidades de datos por parte de los usuarios, a veces sin saberlo. Este script aborda este problema permitiendo a los profesionales de TI determinar r\u00e1pidamente el tama\u00f1o de los perfiles de usuario, garantizando una gesti\u00f3n \u00f3ptima del almacenamiento y la salud del sistema.<\/p>\n<h2>El script para conocer el tama\u00f1o de los perfiles de usuario de Windows y almacenarlos<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Updates a Custom Field with the total size of all User Profiles.\r\n    If the Max parameter is specified then it will return an exit code of 1\r\n     for any profile being over that Max threshold in GB.\r\n.DESCRIPTION\r\n    Updates a Custom Field with the total size of all User Profiles.\r\n    If the Max parameter is specified then it will return an exit code of 1\r\n     for any profile being over that Max threshold in GB.\r\n.EXAMPLE\r\n     -Max 60\r\n    Returns and exit code of 1 if any profile is over 60GB\r\n.EXAMPLE\r\n     -CustomField \"Something\"\r\n    Specifies the name of the custom field to update.\r\n.EXAMPLE\r\n    No Parameter needed.\r\n    Uses the default custom field name: TotalUsersProfileSize\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes:\r\n    Initial Release\r\nBy 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.\r\n    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. \r\n    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. \r\n    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. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n    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. \r\n    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. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [Alias(\"MaxSize\", \"Size\", \"ms\", \"m\", \"s\")]\r\n    [Double]\r\n    $Max,\r\n    [Parameter()]\r\n    [Alias(\"Custom\", \"Field\", \"cf\", \"c\", \"f\")]\r\n    [String]\r\n    $CustomField = \"TotalUsersProfileSize\"\r\n)\r\n\r\nbegin {\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n    function Format-FileSize {\r\n        param($Length)\r\n        switch ($Length) {\r\n            { $_ \/ 1TB -gt 1 } { \"$([Math]::Round(($_ \/ 1TB),2)) TB\"; break }\r\n            { $_ \/ 1GB -gt 1 } { \"$([Math]::Round(($_ \/ 1GB),2)) GB\"; break }\r\n            { $_ \/ 1MB -gt 1 } { \"$([Math]::Round(($_ \/ 1MB),2)) MB\"; break }\r\n            { $_ \/ 1KB -gt 1 } { \"$([Math]::Round(($_ \/ 1KB),2)) KB\"; break }\r\n            Default { \"$_ Bytes\" }\r\n        }\r\n    }\r\n}\r\nprocess {\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Error -Message \"Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    $Profiles = Get-ChildItem -Path \"C:Users\"\r\n    $ProfileSizes = $Profiles | ForEach-Object {\r\n        [PSCustomObject]@{\r\n            Name   = $_.BaseName\r\n            Length = Get-ChildItem -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Property Sum -ExpandProperty Sum\r\n        }\r\n    }\r\n    $Largest = $ProfileSizes | Sort-Object -Property Length -Descending | Select-Object -First 1\r\n\r\n    $Size = $ProfileSizes | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Property Sum -ExpandProperty Sum\r\n\r\n    $FormattedSize = Format-FileSize -Length $Size\r\n\r\n    $AllProfiles = $ProfileSizes | Sort-Object -Property Length -Descending | ForEach-Object {\r\n        $FormattedSizeUser = Format-FileSize -Length $_.Length\r\n        \"$($_.Name) $($FormattedSizeUser)\"\r\n    }\r\n\r\n    Write-Host \"All Profiles - $FormattedSize, $($AllProfiles -join ', ')\"\r\n\r\n    Ninja-Property-Set -Name $CustomField -Value \"$AllProfiles\"\r\n\r\n    if ($Max -and $Max -gt 0) {\r\n        if ($Largest.Length -gt $Max * 1GB) {\r\n            Write-Host \"Found profile over the max size of $Max GB.\"\r\n            Write-Host \"$($Largest.Name) profile is $($Largest.Length \/ 1GB) GB\"\r\n            exit 1\r\n        }\r\n    }\r\n    exit 0\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Accede a m\u00e1s de 300 scripts en el Dojo de NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\/\">Obt\u00e9n acceso<\/a><\/p>\n<\/div>\n<h2>Descripci\u00f3n detallada<\/h2>\n<p>El script para conocer el tama\u00f1o de los perfiles de usuario est\u00e1 segmentado en las siguientes secciones:<\/p>\n<ul>\n<li><strong>Funciones y par\u00e1metros del cmdlet<\/strong>: el script comienza definiendo par\u00e1metros, como <strong>Max<\/strong>, que establece un umbral opcional para el tama\u00f1o del perfil, y <strong>CustomField<\/strong>, que especifica el nombre del campo personalizado que se va a actualizar.<\/li>\n<li><strong>Fase inicial<\/strong>: aqu\u00ed tenemos dos funciones \u00fatiles:\n<ul>\n<li><strong>Test-IsElevated<\/strong>: comprueba si el script para conocer el tama\u00f1o de los perfiles de usuario se ejecuta con privilegios de administrador.<\/li>\n<li><strong>Format-FileSize<\/strong>: convierte los bytes a un formato legible de tama\u00f1o de archivo.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Fase de ejecuci\u00f3n<\/strong>:\n<ul>\n<li>El script para conocer el tama\u00f1o de los perfiles de usuario comprueba si se dispone de privilegios de administrador.<\/li>\n<li>A continuaci\u00f3n, recupera todos los perfiles de usuario de \u00abC:Users\u00bb y calcula su tama\u00f1o.<\/li>\n<li>Los perfiles se clasifican y se calcula el tama\u00f1o total.<\/li>\n<li>Los datos se env\u00edan al host, y la funci\u00f3n &#8216;Ninja-Property-Set&#8217; actualiza el campo personalizado.<\/li>\n<li>Si se especifica un par\u00e1metro Max, el script comprueba si los perfiles superan este tama\u00f1o y sale con un c\u00f3digo apropiado.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2>Posibles casos de uso<\/h2>\n<p>Pensemos en un MSP que supervisa el almacenamiento de un cliente corporativo. De repente, la empresa se enfrenta a problemas de almacenamiento. En lugar de optar por costosas actualizaciones de almacenamiento, el MSP utiliza este script para identificar cualquier perfil de usuario sobredimensionado. Armados con estos datos relativos al tama\u00f1o de los perfiles de usuario, pueden ponerse en contacto con usuarios o departamentos espec\u00edficos para gestionar y racionalizar mejor el almacenamiento.<\/p>\n<h2>Comparaci\u00f3n<\/h2>\n<p>Tradicionalmente, para obtener el total del tama\u00f1o de los perfiles de usuario de Windows era necesario navegar manualmente por las propiedades, aplicaciones de terceros o engorrosos scripts. Este script de PowerShell para conocer el tama\u00f1o de los perfiles de usuario ofrece un enfoque \u00f3ptimo, utilizando las funciones nativas de Windows para obtener informaci\u00f3n precisa y pr\u00e1ctica.<\/p>\n<h2>Preguntas frecuentes<\/h2>\n<ul>\n<li><strong>\u00bfEs obligatorio el privilegio de administrador?<\/strong><br \/>\nS\u00ed, el script requiere privilegios de administrador para ejecutarse.<\/li>\n<li><strong>\u00bfQu\u00e9 ocurre si un perfil de usuario supera el tama\u00f1o m\u00e1ximo especificado?<\/strong><br \/>\nEl script mostrar\u00e1 un mensaje indicando qu\u00e9 perfil excede el tama\u00f1o y devolver\u00e1 un c\u00f3digo de salida de 1.<\/li>\n<li><strong>\u00bfCu\u00e1l es el nombre por defecto del campo personalizado si no se especifica?<\/strong><br \/>\nEs \u00abTotalUsersProfileSize\u00bb.<\/li>\n<\/ul>\n<h2>Implicaciones<\/h2>\n<p>Aunque este script es extremadamente \u00fatil, si no se utiliza de forma correcta, podr\u00eda plantear problemas de privacidad. Extraer y potencialmente compartir tama\u00f1os de perfiles de usuario podr\u00eda ser visto como invasivo por algunos usuarios. Adem\u00e1s, para la seguridad inform\u00e1tica, conocer los patrones de almacenamiento de los usuarios puede ser una forma proactiva de detectar picos inusuales de datos, que podr\u00edan indicar la existencia de malware o de una posible filtraci\u00f3n de datos.<\/p>\n<h2>Recomendaciones<\/h2>\n<ul>\n<li>Ejecuta los scripts de diagn\u00f3sticos siempre fuera de las horas punta para evitar posibles retrasos del sistema.<\/li>\n<li>Aseg\u00farate de haber obtenido los permisos necesarios y de haber informado a las partes interesadas antes de la ejecuci\u00f3n.<\/li>\n<li>Actualiza y mant\u00e9n peri\u00f3dicamente el script para adaptarlo a los cambios en las estructuras y requisitos del sistema.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>Una <a href=\"https:\/\/www.ninjaone.com\/es\/\">plataforma de gesti\u00f3n de TI<\/a> como NinjaOne puede aumentar significativamente la utilidad de este script para conocer el tama\u00f1o de los perfiles de usuario, proporcionando a los profesionales de TI una visi\u00f3n m\u00e1s global de la salud del sistema, el rendimiento y las anomal\u00edas. La integraci\u00f3n de estos scripts en NinjaOne puede ofrecer informaci\u00f3n en tiempo real, haciendo que la gesti\u00f3n del almacenamiento sea m\u00e1s f\u00e1cil.<\/p>\n","protected":false},"author":35,"featured_media":207220,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4267],"class_list":["post-208628","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/208628","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=208628"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/207220"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=208628"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=208628"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=208628"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}