{"id":809301,"date":"2026-05-18T07:39:18","date_gmt":"2026-05-18T07:39:18","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=809301"},"modified":"2026-05-18T07:39:18","modified_gmt":"2026-05-18T07:39:18","slug":"list-all-groups-a-user-belongs-to-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/list-all-groups-a-user-belongs-to-powershell\/","title":{"rendered":"Como listar todos os grupos aos quais um usu\u00e1rio pertence com o PowerShell"},"content":{"rendered":"<p>No cen\u00e1rio em r\u00e1pida evolu\u00e7\u00e3o da TI, o gerenciamento eficaz de usu\u00e1rios e a compreens\u00e3o das fun\u00e7\u00f5es dos usu\u00e1rios continuam sendo essenciais para a seguran\u00e7a e a efici\u00eancia de qualquer organiza\u00e7\u00e3o. Entre as ferramentas dispon\u00edveis para os profissionais de TI, <a href=\"https:\/\/www.ninjaone.com\/blog\/category\/scripts\/\">os scripts do PowerShell<\/a> se destacam como solu\u00e7\u00f5es poderosas para automatizar tarefas. Um desses scripts se concentra em <strong>listar todos os grupos aos quais um usu\u00e1rio pertence<\/strong>.<\/p>\n<h2>Hist\u00f3rico<\/h2>\n<p>As associa\u00e7\u00f5es a grupos de usu\u00e1rios definem os direitos e as permiss\u00f5es que um usu\u00e1rio tem em uma rede. \u00c0 medida que uma organiza\u00e7\u00e3o cresce, manter o controle dessas associa\u00e7\u00f5es torna-se cada vez mais importante. No entanto, isso pode ser complicado e propenso a erros se for feito manualmente. \u00c9 aqui que nosso script do PowerShell se destaca. Especificamente projetado para listar todos os grupos dos quais um usu\u00e1rio \u00e9 membro, esse script \u00e9 inestim\u00e1vel para profissionais de TI e <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">provedores de servi\u00e7os gerenciados (MSPs)<\/a>. Garantir a associa\u00e7\u00e3o correta aos grupos ajuda a evitar a aloca\u00e7\u00e3o excessiva de privil\u00e9gios e sustenta a postura de seguran\u00e7a de uma organiza\u00e7\u00e3o.<\/p>\n<h2>O roteiro<\/h2>\n<p><div class=\"button-wrap orange-button \"><a href=\"#\" data-js=\"button-script-cta\" class=\"button script-cta\" data-js=\"script-cta\"  data-modal=\"200229\" >Email me the script<\/a><\/div><br \/>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 4.0 -RunAsAdministrator\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    This will output the groups that the specified user belongs to.\r\n.DESCRIPTION\r\n    This will output the groups that the specified user belongs to.\r\n.EXAMPLE\r\n     -UserName \"Administrator\" -IsDomainUser\r\n    Will get the groups that the user Administrator belongs to in Active Directory.\r\n.EXAMPLE\r\n     -UserName \"Administrator\"\r\n    Will get the groups that the user Administrator belongs to on the machine it runs on.\r\n.EXAMPLE\r\n    PS C:&gt; Get-User-Membership.ps1 -UserName \"Administrator\"\r\n    Will get the groups that the user Administrator belongs to on the machine it runs on.\r\n.OUTPUTS\r\n    Output (PSCustomObject)\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2012\r\n    If you wish to interact with AD you will need to install RSAT with at least the AD feature.\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 user\r\n    [Parameter(Mandatory = $false)]\r\n    [String]\r\n    $UserName,\r\n    # Modify Local User Membership\r\n    [Parameter(Mandatory = $false)]\r\n    [Switch]\r\n    $IsDomainUser\r\n)\r\n\r\nbegin {}\r\n\r\nprocess {\r\n    if (-not $IsDomainUser) {\r\n        # Get local machine groups\r\n        Get-LocalGroup | ForEach-Object {\r\n            $Group = $_.Name\r\n            # Get users in current group\r\n            # Check that $UserName is a member of this current group and output it to StdOut\/Write-Output\r\n            Get-LocalGroupMember -Group $Group | Where-Object { $_.Name -like \"*$UserName\" } | ForEach-Object {\r\n                [PSCustomObject]@{\r\n                    Group = $Group\r\n                    User  = $_.Name\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            }\r\n            catch {\r\n                Write-Error -Message \"Ninja Agent could not access AD, either RSAT was not installed or that the agent does not have permissions to view users and groups.\"\r\n                exit 5 # Access Denied exit code\r\n            }\r\n            # Get a list of groups that the user is in\r\n            # Loop through each group\r\n            Get-ADGroup -Filter * -ErrorAction SilentlyContinue | ForEach-Object {\r\n                $ADGroup = $_\r\n                # Get users from current group and filter out all other users\r\n                Get-ADGroupMember -Identity $ADGroup -ErrorAction SilentlyContinue | Where-Object {\r\n                    $_.SamAccountName -like $ADUser\r\n                } | ForEach-Object {\r\n                    # Write out to StandardOutput\r\n                    [PSCustomObject]@{\r\n                        Group = $ADGroup.Name\r\n                        User  = $_.SamAccountName\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\/\"\r\n            exit 2 # File Not Found exit code\r\n        }\r\n    }\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n<\/p>\n<div class=\"in-context-cta\"><p>Acesse mais de 300 scripts no NinjaOne Dojo<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/freetrialform\/\">Obter acesso<\/a><\/p>\n<\/div>\n<h2>Detalhamento<\/h2>\n<p>O script pode ser dividido em dois componentes principais com base em sua fun\u00e7\u00e3o:<\/p>\n<ul>\n<li><strong>Verifica\u00e7\u00e3o da associa\u00e7\u00e3o ao grupo local:<\/strong> Se a op\u00e7\u00e3o <strong>-IsDomainUser<\/strong> n\u00e3o for especificada, o script buscar\u00e1 e listar\u00e1 os grupos dos quais o usu\u00e1rio especificado \u00e9 membro no computador local.<\/li>\n<li><strong>Verifica\u00e7\u00e3o de associa\u00e7\u00e3o a grupos do Active Directory:<\/strong> Se a op\u00e7\u00e3o <strong>-IsDomainUser<\/strong> for definida, o script se comunicar\u00e1 com o <a href=\"https:\/\/www.ninjaone.com\/it-hub\/gerenciamento-de-endpoints\/what-is-active-directory\/\">Active Directory<\/a> para buscar e listar os grupos dos quais o usu\u00e1rio especificado faz parte.<\/li>\n<\/ul>\n<p>Durante todo o processo, o script gera os resultados como um PSCustomObject, garantindo que os dados sejam estruturados e possam ser facilmente compreendidos ou processados posteriormente.<\/p>\n<h2>Caso de uso potencial<\/h2>\n<p>Imagine um profissional de TI em uma grande empresa que precisa verificar as associa\u00e7\u00f5es de grupo de um novo chefe de departamento. Usando o script, o profissional de TI pode listar facilmente todos os grupos dos quais o usu\u00e1rio \u00e9 membro, tanto em ambientes locais quanto no Active Directory. Isso garante que o chefe de departamento tenha as permiss\u00f5es corretas, evitando poss\u00edveis viola\u00e7\u00f5es de seguran\u00e7a ou erros de acesso.<\/p>\n<p>Abordagem alternativa<\/p>\n<p>Embora a interface gr\u00e1fica do Active Directory Users and Computers (ADUC) permita a visualiza\u00e7\u00e3o das associa\u00e7\u00f5es de grupos, ela \u00e9 manual e n\u00e3o \u00e9 adequada para verifica\u00e7\u00f5es em massa. Nosso script do PowerShell automatiza essa tarefa, tornando-a eficiente para a verifica\u00e7\u00e3o de v\u00e1rios usu\u00e1rios ou auditorias frequentes. Al\u00e9m disso, com o PowerShell, os resultados podem ser facilmente exportados, filtrados ou integrados a relat\u00f3rios, oferecendo a flexibilidade que falta \u00e0s ferramentas de GUI.<\/p>\n<h2>Implica\u00e7\u00f5es<\/h2>\n<p>A associa\u00e7\u00e3o incorreta a grupos pode levar ao acesso n\u00e3o autorizado a dados ou \u00e0 nega\u00e7\u00e3o de recursos essenciais aos usu\u00e1rios. Ao determinar com precis\u00e3o as associa\u00e7\u00f5es de usu\u00e1rios usando nosso script do PowerShell, os profissionais de TI podem aumentar a seguran\u00e7a e garantir a conformidade regulamentar.<\/p>\n<h2>Recomenda\u00e7\u00f5es<\/h2>\n<ul>\n<li>Sempre execute o script em um ambiente seguro e controlado primeiro.<\/li>\n<li>Audite regularmente as associa\u00e7\u00f5es de grupos de usu\u00e1rios, especialmente para fun\u00e7\u00f5es de alto privil\u00e9gio.<\/li>\n<li>Integrar os resultados do script em uma estrat\u00e9gia mais ampla <a href=\"https:\/\/www.ninjaone.com\/blog\/what-is-identity-access-management-iam\/\">de IAM (Identity and Access Management)<\/a>.<\/li>\n<\/ul>\n<h2>Considera\u00e7\u00f5es finais<\/h2>\n<p>A NinjaOne, com seu conjunto abrangente de solu\u00e7\u00f5es de TI, pode ser um parceiro inestim\u00e1vel na <a href=\"https:\/\/www.ninjaone.com\/pt-br\/\">automa\u00e7\u00e3o, gerenciamento e prote\u00e7\u00e3o de ambientes de TI<\/a>. Quando scripts como o discutido acima s\u00e3o combinados com os recursos do NinjaOne, <a href=\"https:\/\/www.ninjaone.com\/pt-br\/eficiencia\/\">os profissionais de TI podem aumentar sua efici\u00eancia<\/a>, precis\u00e3o e postura de seguran\u00e7a. Essa sinergia abre caminho para uma abordagem proativa do gerenciamento e da seguran\u00e7a de TI.<\/p>\n","protected":false},"author":35,"featured_media":142639,"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":[12435],"class_list":["post-809301","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub\/809301","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/comments?post=809301"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/142639"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=809301"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=809301"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=809301"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}