{"id":257163,"date":"2024-05-21T09:39:19","date_gmt":"2024-05-21T09:39:19","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=257163"},"modified":"2024-05-21T09:39:19","modified_gmt":"2024-05-21T09:39:19","slug":"agregar-o-quitar-usuarios-de-active-directory","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/agregar-o-quitar-usuarios-de-active-directory\/","title":{"rendered":"Agregar o quitar usuarios de Active Directory y grupos de equipos locales con Powershell"},"content":{"rendered":"<p>Gestionar y <strong>modificar la pertenencia de los usuarios a grupos<\/strong>, ya sea en un equipo local o en Active Directory, es una tarea habitual para los profesionales de TI. La gesti\u00f3n eficaz de estas operaciones puede mejorar enormemente la administraci\u00f3n del sistema, agilizando los procesos y evitando errores. En este contexto, el poder de los scripts cobra protagonismo, ofreciendo automatizaci\u00f3n y precisi\u00f3n.<\/p>\n<h2>Antecedentes<\/h2>\n<p>El script proporcionado profundiza en la esencia de la gesti\u00f3n de TI: permite a los administradores a\u00f1adir o eliminar usuarios de grupos espec\u00edficos. Est\u00e1 dise\u00f1ado para ser vers\u00e1til, funcionando tanto en el \u00e1mbito de un ordenador local como en la esfera m\u00e1s amplia de Active Directory. A medida que las empresas y los proveedores de servicios gestionados (MSP) crecen, la gesti\u00f3n manual de usuarios puede resultar ardua. Estos scripts no s\u00f3lo reducen el tiempo dedicado a tareas rutinarias, sino que tambi\u00e9n minimizan los errores humanos.<\/p>\n<h2>El script para agregar o quitar usuarios de Active Directory y grupos de equipos locales<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 2.0\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Add or remove a user to a group in Active Directory or the local computer.\r\n.DESCRIPTION\r\n    Add or remove a user to a group in Active Directory or the local computer.\r\n.EXAMPLE\r\n     -Group \"MyGroup\" -UserName \"MyUser\" -Action Add -IsDomainUser\r\n    Adds MyUser to the group MyGroup in AD.\r\n.EXAMPLE\r\n     -Group \"MyGroup\" -UserName \"MyUser\" -Action Remove -IsDomainUser\r\n    Removes MyUser from the group MyGroup in AD.\r\n.EXAMPLE\r\n     -Group \"MyGroup\" -UserName \"MyUser\" -Action Add\r\n    Adds MyUser to the group MyGroup on the local computer.\r\n.EXAMPLE\r\n    PS C:&gt; Modify-User-Membership.ps1 -Group \"MyGroup\" -UserName \"MyUser\" -Action Remove\r\n    Removes MyUser from the group MyGroup on the local computer.\r\n.OUTPUTS\r\n    String[]\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 7, Windows Server 2012\r\n    This will require RSAT with the AD feature to be installed to function.\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.COMPONENT\r\n    ManageUsers\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    # Specify one Group\r\n    [Parameter(Mandatory = $true)]\r\n    [String]\r\n    $Group,\r\n    # Specify one User\r\n    [Parameter(Mandatory = $true)]\r\n    [String]\r\n    $UserName,\r\n    # Add or Remove user from group\r\n    [Parameter(Mandatory = $true)]\r\n    [ValidateSet(\"Add\", \"Remove\")]\r\n    [String]\r\n    $Action,\r\n    # Modify a domain user's membership\r\n    [Parameter(Mandatory = $false)]\r\n    [Switch]\r\n    $IsDomainUser\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        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))\r\n        { Write-Output $true }\r\n        else\r\n        { Write-Output $false }\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    if (-not $IsDomainUser) {\r\n        # Modify Local User\r\n        if ($Action -like \"Remove\") {\r\n            if ($PSVersionTable.PSVersion.Major -lt 3) {\r\n                # Connect to localhost\r\n                try {\r\n                    $ADSI = [ADSI](\"WinNT:\/\/$env:COMPUTERNAME\")\r\n                }\r\n                catch {\r\n                    Write-Error -Message \"Failed to connect to $env:COMPUTERNAME via ADSI object\"\r\n                    exit 1\r\n                }\r\n                # Find the group\r\n                try {\r\n                    $ASDIGroup = $ADSI.Children.Find($Group, 'group')\r\n                }\r\n                catch {\r\n                    Write-Error -Message \"Failed to find $Group via ADSI object\"\r\n                    exit 1\r\n                }\r\n                # Remove the user from the group\r\n                try {\r\n                    $ASDIGroup.Remove((\"WinNT:\/\/$env:COMPUTERNAME\/$UserName\"))\r\n                }\r\n                catch {\r\n                    Write-Error -Message \"Failed to remove User $UserName from Group $Group\"\r\n                    exit 529 # ERROR_MEMBER_NOT_IN_GROUP\r\n                }\r\n                \r\n            }\r\n            else {\r\n                if (\r\n                    # Check that the group exists\r\n                (Get-LocalGroup -Name $Group -ErrorAction SilentlyContinue) -and\r\n                    # Check that the user exists in the group\r\n                (Get-LocalGroupMember -Group $Group -Member $UserName -ErrorAction SilentlyContinue)\r\n                ) {\r\n                    Write-Output \"Found $UserName in Group $Group, removing.\"\r\n                    try {\r\n                        # Remove user from Group, -Confirm:$false used to not prompt and stop the script\r\n                        Remove-LocalGroupMember -Group $Group -Member $UserName -Confirm:$false\r\n                        Write-Output \"Removed User $UserName from Group $Group\"\r\n                    }\r\n                    catch {\r\n                        Write-Error -Message \"Failed to remove User $UserName from Group $Group\"\r\n                        exit 529 # ERROR_MEMBER_NOT_IN_GROUP\r\n                    }\r\n                }\r\n                elseif (-not (Get-LocalGroup -Name $Group -ErrorAction SilentlyContinue)) {\r\n                    Write-Error -Message \"Group $Group does not exist\"\r\n                    exit 528 # ERROR_NO_SUCH_GROUP\r\n                }\r\n                elseif (-not (Get-LocalGroupMember -Group $Group -Member $UserName -ErrorAction SilentlyContinue)) {\r\n                    Write-Error -Message \"User does not exist in Group $Group\"\r\n                    exit 529 # ERROR_MEMBER_NOT_IN_GROUP\r\n                }\r\n            }\r\n            \r\n        }\r\n        elseif ($Action -like \"Add\") {\r\n            if ($PSVersionTable.PSVersion.Major -lt 3) {\r\n                # Connect to localhost\r\n                try {\r\n                    $ADSI = [ADSI](\"WinNT:\/\/$env:COMPUTERNAME\")\r\n                }\r\n                catch {\r\n                    Write-Error -Message \"Failed to connect to $env:COMPUTERNAME via ADSI object\"\r\n                    exit 1\r\n                }\r\n                # Find the group\r\n                try {\r\n                    $ASDIGroup = $ADSI.Children.Find($Group, 'group')\r\n                }\r\n                catch {\r\n                    Write-Error -Message \"Failed to find $Group via ADSI object\"\r\n                    exit 1\r\n                }\r\n                # Get the members of the group\r\n                $GroupResults = try {\r\n                    $ASDIGroup.psbase.invoke('members')  | ForEach-Object {\r\n                        $_.GetType().InvokeMember(\"Name\", \"GetProperty\", $Null, $_, $Null)\r\n                    }\r\n                }\r\n                catch {\r\n                    $null\r\n                }\r\n                # Check if the user is in the group\r\n                if ($UserName -in $GroupResults) {\r\n                    # User already in Group\r\n                    Write-Output \"User $UserName already in Group $Group\"\r\n                    exit 1320 # ERROR_MEMBER_IN_GROUP\r\n                }\r\n                else {\r\n                    # User not in group, add them to the group\r\n                    try {\r\n                        $ASDIGroup.Add((\"WinNT:\/\/$env:COMPUTERNAME\/$UserName\"))\r\n                    }\r\n                    catch {\r\n                        Write-Error -Message \"Failed to add User $UserName to Group $Group\"\r\n                        exit 1388 # ERROR_INVALID_MEMBER\r\n                    }\r\n                    \r\n                    # We can verify the membership by running the following  command:\r\n                    if ($UserName -in (\r\n                            $ASDIGroup.psbase.invoke('members')  | ForEach-Object {\r\n                                $_.GetType().InvokeMember(\"Name\", \"GetProperty\", $Null, $_, $Null)\r\n                            }\r\n                        )\r\n                    ) {\r\n                        # User in Group\r\n                        Write-Output \"Added User $UserName to Group $Group\"\r\n                    }\r\n                    else {\r\n                        Write-Error -Message \"Failed to add User $UserName to Group $Group\"\r\n                        exit 1388 # ERROR_INVALID_MEMBER\r\n                    }\r\n                }\r\n                \r\n            }\r\n            else {\r\n                # Verify that the user and group exist\r\n                if (\r\n                    # Check that the user exists\r\n                (Get-LocalUser -Name $UserName -ErrorAction SilentlyContinue) -and\r\n                    # Check that the group exists\r\n                (Get-LocalGroup -Name $Group -ErrorAction SilentlyContinue)\r\n                ) {\r\n                    # Check if user is already in group\r\n                    if (-not (Get-LocalGroupMember -Group $Group -Member $UserName -ErrorAction SilentlyContinue)) {\r\n                        # User not in group, good to add\r\n                        try {\r\n                            # Add user to group\r\n                            Add-LocalGroupMember -Group $Group -Member (Get-LocalUser -Name $UserName)\r\n                            Write-Output \"Added User $UserName to Group $Group\"\r\n                        }\r\n                        catch {\r\n                            Write-Error -Message \"Failed to add User $UserName to Group $Group\"\r\n                            exit 1388 # ERROR_INVALID_MEMBER\r\n                        }\r\n                    }\r\n                    else {\r\n                        # User already in Group\r\n                        Write-Output \"User $UserName already in Group $Group\"\r\n                        exit 1320 # ERROR_MEMBER_IN_GROUP\r\n                    }\r\n                \r\n                }\r\n            }\r\n        }\r\n    }\r\n    else {\r\n        if ((Get-Module -Name ActiveDirectory -ListAvailable -ErrorAction SilentlyContinue)) {\r\n            try {\r\n                Import-Module -Name ActiveDirectory\r\n                # Get most of our data needed for the logic, and to reduce the number of time we need to talk to AD\r\n                $ADUser = (Get-ADUser -Identity $UserName -Properties SamAccountName -ErrorAction SilentlyContinue).SamAccountName\r\n                $ADGroup = Get-ADGroup -Identity $Group -ErrorAction SilentlyContinue\r\n                $ADInGroup = Get-ADGroupMember -Identity $Group -ErrorAction SilentlyContinue | Where-Object { $_.SamAccountName -like $ADUser }\r\n            }\r\n            catch {\r\n                Write-Error -Message \"Ninja Agent could not access AD, please check that the agent has permissions to add and remove users from groups.\"\r\n                exit 5 # Access Denied exit code\r\n            }\r\n            \r\n            # Modify AD User\r\n            if ($Action -like \"Remove\") {\r\n                # Verify that the user and group exist, and if the user is in the group\r\n                if (\r\n                    $ADUser -and\r\n                    # Check that the group exists\r\n                    $ADGroup -and\r\n                    # Check that the user exists in the group\r\n                    $ADInGroup\r\n                ) {\r\n                    Write-Output \"Found $UserName in Group $Group, removing.\"\r\n                    try {\r\n                        # Remove user from Group, -Confirm:$false used to not prompt and stop the script\r\n                        Remove-ADGroupMember -Identity $Group -Members $ADUser -Confirm:$false\r\n                        Write-Output \"Removed User $UserName from Group $Group\"\r\n                    }\r\n                    catch {\r\n                        Write-Error -Message \"Failed to remove User $UserName from Group $Group\"\r\n                        exit 529 # ERROR_MEMBER_NOT_IN_GROUP\r\n                    }\r\n                }\r\n                elseif (-not $ADGroup) {\r\n                    Write-Error -Message \"Group $Group does not exist\"\r\n                    exit 528 # ERROR_NO_SUCH_GROUP\r\n                }\r\n                elseif (-not $ADInGroup) {\r\n                    Write-Error -Message \"User does not exist in Group $Group\"\r\n                    exit 529 # ERROR_MEMBER_NOT_IN_GROUP\r\n                }\r\n            }\r\n            elseif ($Action -like \"Add\") {\r\n                # Verify that the user and group exist\r\n                if (\r\n                    # Check that the user exists\r\n                    $ADUser -and\r\n                    # Check that the group exists\r\n                    $ADGroup\r\n                ) {\r\n                    # Check if user is already in group\r\n                    if (-not $ADInGroup) {\r\n                        # User not in group, good to add\r\n                        try {\r\n                            # Add user to group\r\n                            Add-ADGroupMember -Identity $Group -Members $ADUser\r\n                            Write-Output \"Added User $UserName to Group $Group\"\r\n                        }\r\n                        catch {\r\n                            Write-Error -Message \"Failed to add User $UserName to Group $Group\"\r\n                            exit 1388 # ERROR_INVALID_MEMBER\r\n                        }\r\n                    }\r\n                    else {\r\n                        # User already in Group\r\n                        Write-Output \"User $UserName already in Group $Group\"\r\n                        exit 1320 # ERROR_MEMBER_IN_GROUP\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            # Throw error that RSAT: ActiveDirectory isn't installed\r\n            Write-Error -Message \"RSAT: ActiveDirectory is not installed or not found on this computer. The PowerShell Module called ActiveDirectory is needed to proceed.\" -RecommendedAction \"https:\/\/docs.microsoft.com\/en-us\/powershell\/module\/activedirectory\/?view=windowsserver2019-ps\"\r\n            exit 2 # File Not Found exit code\r\n        }\r\n    }\r\n}\r\n\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p style=\"text-align: center;\">Accede a m\u00e1s de 300 scripts en el Dojo de NinjaOne<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\/\">Obt\u00e9n acceso<\/a><\/p>\n<\/div>\n<h2>An\u00e1lisis detallado<\/h2>\n<p>El script para agregar o quitar usuarios de Active Directory y grupos de equipos locales comienza con un comentario exhaustivo que ofrece informaci\u00f3n sobre sus funcionalidades, ejemplos y requisitos. Se definen par\u00e1metros esenciales como Group, UserName, Action y un modificador opcional IsDomainUser, que controlan la l\u00f3gica principal. Una funci\u00f3n de ayuda, Test-IsElevated, comprueba si el script se ejecuta con privilegios administrativos. La l\u00f3gica principal se inicia con una comprobaci\u00f3n de elevaci\u00f3n, seguida de si la tarea concierne a un usuario local o a un usuario de Active Directory. Dependiendo de la versi\u00f3n de PowerShell y de la acci\u00f3n deseada (Agregar\/Quitar), el script interact\u00faa con <a href=\"https:\/\/learn.microsoft.com\/en-us\/windows\/win32\/adsi\/active-directory-service-interfaces-adsi\" target=\"_blank\" rel=\"noopener\">Interfaces de servicio de Active Directory (ADSI)<\/a> o emplea cmdlets nativos de PowerShell.\u00a0Para los usuarios de Active Directory, se emplea el m\u00f3dulo Active Directory, que ofrece una integraci\u00f3n y gesti\u00f3n perfectas.<\/p>\n<h2>Posibles casos de uso<\/h2>\n<p>Estudio de caso:<\/p>\n<p>Sara, administradora de TI en una empresa en expansi\u00f3n, necesita incorporar a 50 nuevos empleados. Dado que los departamentos y las funciones var\u00edan, la asignaci\u00f3n manual de usuarios a los respectivos grupos de AD llevar\u00eda mucho tiempo. Con este script para agregar o quitar usuarios de Active Directory y grupos de equipos locales, Sara asigna r\u00e1pidamente los usuarios a sus respectivos grupos, garantizando que los controles de acceso se apliquen de forma eficaz. Durante las auditor\u00edas inform\u00e1ticas trimestrales, tambi\u00e9n utiliza el script para eliminar usuarios de grupos espec\u00edficos o de los equipos locales de empleados que han dejado la empresa.<\/p>\n<h2>Comparaciones<\/h2>\n<p>La gesti\u00f3n tradicional de usuarios suele girar en torno a herramientas basadas en GUI como Usuarios y equipos de Active Directory (ADUC) o Administraci\u00f3n de equipos para usuarios locales. Aunque son f\u00e1ciles de usar, no son eficaces para las operaciones a gran escala. Este script de PowerShell para agregar o quitar usuarios de Active Directory y grupos de equipos locales garantiza que tareas que llevar\u00edan horas se reduzcan a meros minutos. Sin embargo, a diferencia de las herramientas GUI que proporcionan informaci\u00f3n visual, el script requiere pruebas exhaustivas para garantizar que no se produzcan acciones involuntarias.<\/p>\n<h2>FAQ<\/h2>\n<ul>\n<li><strong>\u00bfPuedo utilizar este script en versiones anteriores de PowerShell?<\/strong><br \/>\nS\u00ed, el script es compatible con versiones de PowerShell tan antiguas como la 2.0. Sin embargo, la funcionalidad puede variar en funci\u00f3n de la versi\u00f3n.<\/li>\n<li><strong>\u00bfEs obligatorio el m\u00f3dulo Active Directory?<\/strong><br \/>\nPara las acciones relativas a los usuarios del dominio, es necesario el m\u00f3dulo Active Directory.<\/li>\n<li><strong>\u00bfC\u00f3mo puedo asegurarme de que tengo los derechos administrativos necesarios?<\/strong><br \/>\nEl script contiene comprobaciones integradas de derechos administrativos y proporcionar\u00e1 un mensaje de error si no se ejecuta con los privilegios necesarios.<\/li>\n<\/ul>\n<h2>Implicaciones<\/h2>\n<p>El script para agregar o quitar usuarios de Active Directory y grupos de equipos locales puede reducir dr\u00e1sticamente los errores en la gesti\u00f3n de grupos de usuarios, lo que puede tener importantes implicaciones para la seguridad inform\u00e1tica. Garantizar que los usuarios s\u00f3lo formen parte de los grupos necesarios refuerza el principio del m\u00ednimo privilegio, piedra angular de la seguridad de TI. Sin embargo, la automatizaci\u00f3n conlleva la responsabilidad de garantizar que los scripts no proporcionen inadvertidamente un acceso excesivo, abriendo potencialmente las puertas a violaciones de la seguridad.<\/p>\n<h2>Recomendaciones<\/h2>\n<ul>\n<li>Prueba siempre el script en un entorno controlado antes de desplegarlo en producci\u00f3n.<\/li>\n<li>Mant\u00e9n un registro de todos los cambios realizados con el script con fines de auditor\u00eda.<\/li>\n<li>Aseg\u00farate de que dispones de copias de seguridad de Active Directory o de las bases de datos de usuarios locales para revertir cualquier cambio involuntario.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>A medida que los entornos de TI se vuelven m\u00e1s complejos, herramientas como NinjaOne son fundamentales para ofrecer soluciones integrales. Para tareas como la gesti\u00f3n de grupos de usuarios, scripts como el que hemos analizado anteriormente pueden <a href=\"https:\/\/www.ninjaone.com\/es\/\">integrarse en plataformas como NinjaOne<\/a>, garantizando que los administradores de TI tengan las mejores herramientas a su alcance, automatizando y agilizando los procesos a la vez que mantienen una seguridad \u00f3ptima.<\/p>\n","protected":false},"author":35,"featured_media":144289,"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-257163","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\/257163","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=257163"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/144289"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=257163"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=257163"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=257163"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}