{"id":810199,"date":"2026-05-20T14:11:52","date_gmt":"2026-05-20T14:11:52","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=810199"},"modified":"2026-05-20T14:11:52","modified_gmt":"2026-05-20T14:11:52","slug":"como-monitorar-o-ultimo-logon-de-um-usuario-com-o-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/como-monitorar-o-ultimo-logon-de-um-usuario-com-o-powershell\/","title":{"rendered":"Como monitorar o \u00faltimo logon de um usu\u00e1rio com o PowerShell"},"content":{"rendered":"<p>No gerenciamento moderno de TI, uma das tarefas essenciais envolve o monitoramento de contas de usu\u00e1rios, especialmente a identifica\u00e7\u00e3o de contas inativas. Esse empreendimento \u00e9 mais do que apenas um servi\u00e7o de limpeza. Ele est\u00e1 diretamente ligado \u00e0 seguran\u00e7a, \u00e0 conformidade e ao gerenciamento eficiente de recursos. Hoje, vamos nos aprofundar em um script <a href=\"https:\/\/www.ninjaone.com\/it-hub\/gerenciamento-de-endpoints\/what-is-powershell\/\">do PowerShell<\/a> que\u00a0permite <strong>monitorar o \u00faltimo logon de um usu\u00e1rio<\/strong><\/p>\n<h2>Hist\u00f3rico<\/h2>\n<p>O script fornecido foi projetado para identificar e gerar relat\u00f3rios sobre contas de usu\u00e1rio com base no \u00faltimo hor\u00e1rio de logon, especialmente aquelas que n\u00e3o foram usadas por um per\u00edodo espec\u00edfico. Garantir que as contas n\u00e3o utilizadas sejam identificadas e gerenciadas \u00e9 fundamental para os profissionais de TI e para os <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">provedores de servi\u00e7os gerenciados (MSPs)<\/a>. As contas inativas representam riscos \u00e0 seguran\u00e7a e, muitas vezes, tornam-se alvos f\u00e1ceis para os criminosos cibern\u00e9ticos. Al\u00e9m disso, para organiza\u00e7\u00f5es sujeitas a normas de conformidade, o rastreamento da atividade do usu\u00e1rio e a desativa\u00e7\u00e3o de contas n\u00e3o utilizadas podem ser um requisito.<\/p>\n<h2>O roteiro<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 90 days or a custom amount of days.\r\n.DESCRIPTION\r\n    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 90 days or a custom amount of days.\r\n.EXAMPLE\r\n    No parameters needed.\r\n    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 90 days.\r\n.EXAMPLE\r\n    -IncludeDisabled\r\n    Returns exit code of 1 if any Enabled or Disabled accounts that haven't been logged in over 90 days.\r\n.EXAMPLE\r\n    -Days 60\r\n    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 60 days.\r\n.EXAMPLE\r\n    -Days 60 -IncludeDisabled\r\n    Returns exit code of 1 if any Enabled or Disabled accounts that haven't been logged in over 60 days.\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 7, Windows Server 2012\r\n    Exit code 1: Found users that haven't logged in over X days and are enabled.\r\n    Exit code 2: Calling \"net.exe user\" or \"Get-LocalUser\" failed.\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    [Parameter()]\r\n    [int]\r\n    $Days = 90,\r\n    [Parameter()]\r\n    [switch]\r\n    $IncludeDisabled\r\n)\r\n\r\nbegin {}\r\nprocess {\r\n    if ($Days -lt 0) {\r\n        # Change negative days to the expected positive days\r\n        $Days = 0 - $Days\r\n    }\r\n    $Accounts = if ($(Get-Command \"Get-LocalUser\").Name -like \"Get-LocalUser\") {\r\n        try {\r\n            Get-LocalUser | Select-Object Name, Enabled, SID, LastLogon\r\n        }\r\n        catch {\r\n            exit 2\r\n        }\r\n    }\r\n    else {\r\n        # Get users from net.exe user\r\n        $Data = $(net.exe user) | Select-Object -Skip 4\r\n        # Check if the command ran the way we wanted and the exit code is 0\r\n        if ($($Data | Select-Object -Last 2 | Select-Object -First 1) -like \"*The command completed successfully.*\" -and $LASTEXITCODE -eq 0) {\r\n            # Process the output and get only the users\r\n            $Users = $Data[0..($Data.Count - 3)] -split 's+' | Where-Object { -not $([String]::IsNullOrEmpty($_)) }\r\n            # Loop through each user\r\n            $Users | ForEach-Object {\r\n                # Get the Account active property look for a Yes\r\n                $Enabled = $(net.exe user $_) | Where-Object {\r\n                    $_ -like \"Account active*\" -and\r\n                    $($_ -split 's+' | Select-Object -Last 1) -like \"Yes\"\r\n                }\r\n                # Get the Last logon property\r\n                $LastLogon = $(\r\n                    $(\r\n                        $(net.exe user $_) | Where-Object {\r\n                            $_ -like \"Last logon*\"\r\n                        }\r\n                    ) -split 's+' | Select-Object -Skip 2\r\n                ) -join ' '\r\n                # Get the Password last set property\r\n                $PasswordLastSet = $(\r\n                    $(\r\n                        $(net.exe user $_) | Where-Object {\r\n                            $_ -like \"Password last set*\"\r\n                        }\r\n                    ) -split 's+' | Select-Object -Skip 3\r\n                ) -join ' '\r\n                # Output Name and Enabled almost like how Get-LocalUser displays it's data\r\n                [PSCustomObject]@{\r\n                    Name      = $_\r\n                    Enabled   = if ($Enabled -like \"*Yes*\") { $true }else { $false }\r\n                    LastLogon = if ($LastLogon -like \"*Never*\") { [DateTime]::Parse($PasswordLastSet) } else { [DateTime]::Parse($LastLogon) }\r\n                }\r\n            }\r\n        }\r\n        else {\r\n            exit 2\r\n        }\r\n    }\r\n    $Output = $Accounts | Where-Object {\r\n        if ($IncludeDisabled) {\r\n            $_.LastLogon -lt $(Get-Date).AddDays(0 - $Days)\r\n        }\r\n        else {\r\n            $_.Enabled -and $_.LastLogon -lt $(Get-Date).AddDays(0 - $Days)\r\n        }\r\n    }\r\n    $Output | Out-String | Write-Host\r\n    if ($null -ne $Output) {\r\n        exit 1\r\n    }\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p style=\"text-align: center;\">Acesse mais de 300 scripts no NinjaOne Dojo<\/p>\n<p style=\"text-align: center;\"><a href=\"https:\/\/www.ninjaone.com\/freetrialform\/\">Obter acesso<\/a><\/p>\n<\/div>\n<h2>Detalhamento<\/h2>\n<p>O script come\u00e7a definindo uma dura\u00e7\u00e3o padr\u00e3o de 90 dias para verificar a inatividade. Em seguida, ele usa o cmdlet<strong>&#8220;Get-LocalUser<\/strong>&#8221; ou o comando<strong>&#8220;net.exe user<\/strong> &#8220;, dependendo do que estiver dispon\u00edvel.<\/p>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\">Se o cmdlet &#8220;Get-LocalUser&#8221; estiver presente, ele buscar\u00e1 os detalhes diretamente.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\">Caso contr\u00e1rio, ele recorre ao comando &#8220;net.exe user&#8221;. Esse comando recupera os dados e, em seguida, processa a sa\u00edda para filtrar os detalhes necess\u00e1rios.<\/li>\n<\/ul>\n<p>A l\u00f3gica principal \u00e9 verificar se a data do \u00faltimo logon de cada usu\u00e1rio \u00e9 mais antiga do que o limite definido. Se for encontrada uma correspond\u00eancia, ela ser\u00e1 exibida e o script ser\u00e1 encerrado com o c\u00f3digo 1. Um c\u00f3digo de sa\u00edda de 2 \u00e9 usado para exce\u00e7\u00f5es ao buscar dados do usu\u00e1rio.<\/p>\n<h2>Casos de uso em potencial<\/h2>\n<p>Imagine Jane, uma profissional de TI em uma empresa de m\u00e9dio porte. Recentemente, a empresa enfrentou uma pequena viola\u00e7\u00e3o de seguran\u00e7a. Ap\u00f3s o incidente, Jane foi encarregada de refor\u00e7ar a seguran\u00e7a. Uma das sugest\u00f5es foi verificar regularmente as contas que estavam inativas e desativ\u00e1-las. Usando esse script, ela pode configurar uma rotina mensal para obter uma lista dessas contas, garantindo que o diret\u00f3rio de usu\u00e1rios da empresa permane\u00e7a ativo e seguro.<\/p>\n<h2>Compara\u00e7\u00f5es<\/h2>\n<p>Embora o script utilize o PowerShell, outra abordagem poderia envolver a consulta direta ao <a href=\"https:\/\/www.ninjaone.com\/it-hub\/gerenciamento-de-endpoints\/what-is-active-directory\/\">Active Directory<\/a> (se dispon\u00edvel) para obter detalhes da conta do usu\u00e1rio. Podem ser usadas ferramentas como o ADManager Plus ou at\u00e9 mesmo o Active Directory Users and Computers (ADUC) integrado. No entanto, nosso script oferece uma alternativa leve, personaliz\u00e1vel e gratuita.<\/p>\n<h2>Implica\u00e7\u00f5es<\/h2>\n<p>Al\u00e9m de identificar contas inativas, a implica\u00e7\u00e3o mais ampla desse script est\u00e1 relacionada \u00e0 seguran\u00e7a de TI. As contas inativas podem ser facilmente comprometidas, fornecendo acesso n\u00e3o autorizado. Verifica\u00e7\u00f5es peri\u00f3dicas da inatividade do usu\u00e1rio e a\u00e7\u00f5es apropriadas podem evitar poss\u00edveis viola\u00e7\u00f5es.<\/p>\n<h2>Recomenda\u00e7\u00f5es<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\">Sempre teste o script em um <a href=\"https:\/\/www.ninjaone.com\/it-hub\/seguranca-de-endpoints\/what-is-a-sandbox\/\">ambiente sandbox<\/a> antes de implement\u00e1-lo em uma configura\u00e7\u00e3o ativa.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\">Programe esse script para ser executado periodicamente para garantir o monitoramento cont\u00ednuo.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\">Ao identificar contas inativas, tome as medidas adequadas, como desativar a conta ou notificar o usu\u00e1rio ou seu gerente.<\/li>\n<\/ul>\n<h2>Considera\u00e7\u00f5es finais<\/h2>\n<p>Embora o script forne\u00e7a uma solu\u00e7\u00e3o eficiente, a integra\u00e7\u00e3o de ferramentas como o <a href=\"https:\/\/www.ninjaone.com\/pt-br\/\">NinjaOne<\/a> pode aprimorar ainda mais os recursos, tornando as tarefas mais automatizadas e fornecendo um <a href=\"https:\/\/www.ninjaone.com\/pt-br\/gerenciamento-de-endpoints\/\">painel de controle centralizado para o gerenciamento<\/a>. Ferramentas como o NinjaOne foram projetadas para lidar com essas tarefas de forma eficiente, garantindo que os profissionais de TI, como Jane, possam se concentrar em tarefas mais estrat\u00e9gicas, aproveitando scripts como o acima como parte de um kit de ferramentas mais amplo.<\/p>\n","protected":false},"author":35,"featured_media":144300,"parent":0,"menu_order":0,"comment_status":"open","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-810199","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\/810199","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=810199"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/144300"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=810199"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=810199"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=810199"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}