{"id":809297,"date":"2026-05-18T07:37:17","date_gmt":"2026-05-18T07:37:17","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=809297"},"modified":"2026-05-18T07:37:17","modified_gmt":"2026-05-18T07:37:17","slug":"encontrar-tentativas-de-login-fracassadas-no-windows-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/encontrar-tentativas-de-login-fracassadas-no-windows-powershell\/","title":{"rendered":"Como localizar tentativas de login com falha no Windows usando o PowerShell"},"content":{"rendered":"<p>Garantir a seguran\u00e7a dos sistemas de TI \u00e9 uma tarefa crucial. A identifica\u00e7\u00e3o de atividades suspeitas, como v\u00e1rias tentativas de login fracassadas, \u00e9 uma medida importante para atenuar poss\u00edveis amea\u00e7as. O script fornecido, escrito no PowerShell, serve como uma ferramenta vers\u00e1til para ajudar os profissionais de TI e MSPs a <strong>obter insights sobre eventos de login com falha<\/strong>.<\/p>\n<h2>Hist\u00f3rico<\/h2>\n<p>Compreender as tentativas de login com falha em um sistema pode fornecer insights cruciais para os administradores de TI. Eles podem detectar poss\u00edveis viola\u00e7\u00f5es de seguran\u00e7a, monitorar o comportamento dos usu\u00e1rios e manter a integridade do sistema. O script do PowerShell fornecido obt\u00e9m esses dados com efici\u00eancia, oferecendo uma solu\u00e7\u00e3o robusta para profissionais. Nunca \u00e9 demais enfatizar a import\u00e2ncia dessa ferramenta. Com o aumento das amea\u00e7as \u00e0 seguran\u00e7a cibern\u00e9tica, ter um m\u00e9todo eficiente para detectar anomalias nos logins de usu\u00e1rios torna-se essencial para MSPs e profissionais de TI.<\/p>\n<h2>O roteiro<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 3.0 -RunAsAdministrator\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Returns the number of recent failed login attempts.\r\n.DESCRIPTION\r\n    Returns the number of recent failed login attempts of all users or of a specific user. If a user is specified then just a number is returned.\r\n.EXAMPLE\r\n    No parameters needed.\r\n    Returns all users, of the local machine, with a could of failed login attempts.\r\nOutput Example:\r\nUserName  FailedLoginAttempts\r\n--------  -------------------\r\nFred                        4\r\nBob                         0\r\n.EXAMPLE\r\n     -UserName \"Fred\"\r\n    Returns the number of failed login attempts of the user Fred on the local machine.\r\nOutput Example:\r\n4\r\n.EXAMPLE\r\n     -ComputerName \"FredPC\" -UserName \"Fred\"\r\n    Returns the number of failed login attempts of the user Fred on the computer named FredPC.\r\nOutput Example:\r\n4\r\n.EXAMPLE\r\n     -ComputerName \"FredPC\" -UserName \"Fred\" -Detailed\r\n    Returns the number of failed login attempts of the user Fred on the computer named FredPC, but will more details of each failed and successful logins.\r\nOutput Example:\r\n\r\nTimeGenerated   : 10\/18\/2019 7:52:43 AM\r\nEventID         : 4624\r\nCategory        : 12544\r\nADUsername      : Fred\r\nDomain          : FredPC\r\nUserSID         : S-1-0-0\r\nWorkstation     : -\r\nSourceIP        : -\r\nPort            : -\r\nFailureReason   : Interactive\r\nFailureStatus   : Incorrect password\r\nFailureSubStatus: Other\r\n.EXAMPLE\r\n    PS C:&gt; Monitor-Failed-Password-Attempts.ps1 -ComputerName \"FredPC\" -UserName \"Fred\"\r\n    Returns the number of failed login attempts of the user Fred on the computer named FredPC.\r\nOutput Example:\r\n4\r\n.OUTPUTS\r\n    System.Int32 Number of failed login attempts.\r\n.OUTPUTS\r\n    PSCustomObject List of user names and a count of failed login attempts.\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 7, Windows Server 2012\r\n    If ComputerName is specified, then be sure that the computer that this script is running on has network and permissions to access the Event Log on the remote computer.\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\nparam (\r\n    # The name of a remote computer to get event logs for failed logins\r\n    [Parameter(Mandatory = $false)]\r\n    [String]\r\n    $ComputerName = [System.Net.Dns]::GetHostName(),\r\n    # A username\r\n    [Parameter(Mandatory = $false)]\r\n    [String]\r\n    $UserName,\r\n    # Returns all relevant events, sorted by TimeGenerated\r\n    [Switch]\r\n    $Detailed\r\n)\r\n\r\n# Support functions\r\n# Returns the matching FailureReason like Incorrect password\r\nfunction Get-FailureReason {\r\n    Param($FailureReason)\r\n    switch ($FailureReason) {\r\n        '0xC0000064' { \"Account does not exist\"; break; }\r\n        '0xC000006A' { \"Incorrect password\"; break; }\r\n        '0xC000006D' { \"Incorrect username or password\"; break; }\r\n        '0xC000006E' { \"Account restriction\"; break; }\r\n        '0xC000006F' { \"Invalid logon hours\"; break; }\r\n        '0xC000015B' { \"Logon type not granted\"; break; }\r\n        '0xc0000070' { \"Invalid Workstation\"; break; }\r\n        '0xC0000071' { \"Password expired\"; break; }\r\n        '0xC0000072' { \"Account disabled\"; break; }\r\n        '0xC0000133' { \"Time difference at DC\"; break; }\r\n        '0xC0000193' { \"Account expired\"; break; }\r\n        '0xC0000224' { \"Password must change\"; break; }\r\n        '0xC0000234' { \"Account locked out\"; break; }\r\n        '0x0' { \"0x0\"; break; }\r\n        default { \"Other\"; break; }\r\n    }\r\n}\r\nfunction Get-LogonType {\r\n    Param($LogonType)\r\n    switch ($LogonType) {\r\n        '0' { 'Interactive'; break; }\r\n        '2' { 'Interactive'; break; }\r\n        '3' { 'Network'; break; }\r\n        '4' { 'Batch'; break; }\r\n        '5' { 'Service'; break; }\r\n        '6' { 'Proxy'; break; }\r\n        '7' { 'Unlock'; break; }\r\n        '8' { 'Networkcleartext'; break; }\r\n        '9' { 'NewCredentials'; break; }\r\n        '10' { 'RemoteInteractive'; break; }\r\n        '11' { 'CachedInteractive'; break; }\r\n        '12' { 'CachedRemoteInteractive'; break; }\r\n        '13' { 'CachedUnlock'; break; }\r\n        Default {}\r\n    }\r\n}\r\n#-Newest $Records\r\n$Events = Get-EventLog -ComputerName $ComputerName -LogName 'security' -InstanceId 4625, 4624 | Sort-Object -Property TimeGenerated | ForEach-Object {\r\n    if ($_.InstanceId -eq 4625) {\r\n        $_ | Select-Object -Property @(\r\n            @{Label = 'TimeGenerated'; Expression = { $_.TimeGenerated } },\r\n            @{Label = 'EventID'; Expression = { $_.InstanceId } },\r\n            @{Label = 'Category'; Expression = { $_.CategoryNumber } },\r\n            @{Label = 'Username'; Expression = { $_.ReplacementStrings[5] } },\r\n            @{Label = 'Domain'; Expression = { $_.ReplacementStrings[6] } },\r\n            @{Label = 'UserSID'; Expression = { (($_.Message -Split 'rn' | Select-String 'Security ID')[1] -Split 's+')[3] } },\r\n            # @{Label = 'UserSID'; Expression = { $_.ReplacementStrings[0] } },\r\n            @{Label = 'Workstation'; Expression = { $_.ReplacementStrings[13] } },\r\n            @{Label = 'SourceIP'; Expression = { $_.ReplacementStrings[19] } },\r\n            @{Label = 'Port'; Expression = { $_.ReplacementStrings[20] } },\r\n            @{Label = 'LogonType'; Expression = { $_.ReplacementStrings[8] } },\r\n            @{Label = 'FailureStatus'; Expression = { Get-FailureReason($_.ReplacementStrings[7]) } },\r\n            @{Label = 'FailureSubStatus'; Expression = { Get-FailureReason($_.ReplacementStrings[9]) } }\r\n        )\r\n    }\r\n    elseif ($_.InstanceId -eq 4624 -and (Get-LogonType($_.ReplacementStrings[8])) -notlike 'Service') {\r\n        $_ | Select-Object -Property @(\r\n            @{Label = 'TimeGenerated'; Expression = { $_.TimeGenerated } },\r\n            @{Label = 'EventID'; Expression = { $_.InstanceId } },\r\n            @{Label = 'Category'; Expression = { $_.CategoryNumber } },\r\n            @{Label = 'Username'; Expression = { $_.ReplacementStrings[5] } },\r\n            @{Label = 'Domain'; Expression = { $_.ReplacementStrings[6] } },\r\n            @{Label = 'UserSID'; Expression = { $_.ReplacementStrings[0] } },\r\n            @{Label = 'Workstation'; Expression = { $_.ReplacementStrings[11] } },\r\n            @{Label = 'SourceIP'; Expression = { $_.ReplacementStrings[18] } },\r\n            @{Label = 'Port'; Expression = { $_.ReplacementStrings[19] } },\r\n            @{Label = 'LogonType'; Expression = { Get-LogonType($_.ReplacementStrings[8]) } },\r\n            @{Label = 'LogonID'; Expression = { Get-FailureReason($_.ReplacementStrings[7]) } },\r\n            @{Label = 'LogonProcess'; Expression = { Get-FailureReason($_.ReplacementStrings[9]) } }\r\n        )\r\n    }\r\n}\r\n\r\nif ($Detailed) {\r\n    if ($UserName) {\r\n        $Events | Where-Object {\r\n            $_.Username -like $UserName\r\n        }\r\n    }\r\n    else {\r\n        $Events | Where-Object {\r\n            $_.Username -notlike \"DWM*\" -and\r\n            $_.Username -notlike \"UMFD*\" -and\r\n            $_.Username -notlike \"SYSTEM\"\r\n        }\r\n    }\r\n}\r\nelse {\r\n    $UserNames = if ($UserName) {\r\n        ($Events | Select-Object -Property Username -Unique).Username | Where-Object {\r\n            $_ -like \"$UserName\"\r\n        }\r\n    }\r\n    else {\r\n        ($Events | Select-Object -Property Username -Unique).Username | Where-Object {\r\n            $_ -notlike \"DWM*\" -and\r\n            $_ -notlike \"UMFD*\" -and\r\n            $_ -notlike \"SYSTEM\"\r\n        }\r\n    }\r\n    \r\n    $UserNames | ForEach-Object {\r\n        $CurrentUserName = $_\r\n        $FailedLoginCount = 0\r\n        for ($i = 0; $i -lt $Events.Count; $i++) {\r\n            if ($Events[$i].EventID -eq 4625 -and $Events[$i].Username -like $CurrentUserName) {\r\n                # User failed to login X times\r\n                # Count the number of failed logins\r\n                $FailedLoginCount++\r\n            }\r\n            elseif ($Events[$i].EventID -eq 4624 -and $Events[$i].Username -like $CurrentUserName) {\r\n                # User logged in successfully\r\n                # Reset the number of failed logins to 0\r\n                $FailedLoginCount = 0\r\n            }\r\n        }\r\n        if ($UserName) {\r\n            # If a UserName was specified, then return only the failed login count\r\n            $FailedLoginCount\r\n        }\r\n        else {\r\n            # If no UserName was specified, then return the user name and failed login count\r\n            [PSCustomObject]@{\r\n                UserName            = $CurrentUserName\r\n                FailedLoginAttempts = $FailedLoginCount\r\n            }\r\n        }\r\n    }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n\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>An\u00e1lise detalhada do roteiro<\/h2>\n<p>Em sua ess\u00eancia, o script obt\u00e9m dados dos logs de eventos de um determinado computador, visando IDs de eventos espec\u00edficos que representam tentativas de login fracassadas e bem-sucedidas.<\/p>\n<ul>\n<li><strong>Par\u00e2metros<\/strong>: O script come\u00e7a definindo par\u00e2metros como <strong>ComputerName<\/strong>, <strong>UserName<\/strong> e <strong>Detailed<\/strong>. Isso permite que o usu\u00e1rio especifique a m\u00e1quina, o usu\u00e1rio e o n\u00edvel de detalhe das tentativas de login.<\/li>\n<li><strong>Fun\u00e7\u00f5es<\/strong>: Duas fun\u00e7\u00f5es, <strong>Get-FailureReason<\/strong> e <strong>Get-LogonType<\/strong>, traduzem as informa\u00e7\u00f5es codificadas dos registros de eventos em dados leg\u00edveis por humanos sobre o tipo de login e o motivo da falha no login.<\/li>\n<li><strong>Obten\u00e7\u00e3o de eventos<\/strong>: Em seguida, o script obt\u00e9m os registros de eventos, filtrando-os para reter apenas as informa\u00e7\u00f5es necess\u00e1rias. Isso envolve selecionar as inst\u00e2ncias com as IDs de evento relevantes.<\/li>\n<li><strong>Processamento<\/strong>: Dependendo da solicita\u00e7\u00e3o de dados detalhados, o script fornece um detalhamento abrangente de cada tentativa de login ou um resumo das tentativas fracassadas de cada usu\u00e1rio.<\/li>\n<\/ul>\n<h2>Casos de uso em potencial<\/h2>\n<p>Imagine um administrador de TI em uma empresa de m\u00e9dio porte. Recentemente, o departamento de TI notou um aumento no n\u00famero de tentativas de login com falha, especialmente fora do hor\u00e1rio de trabalho. Usando o script, o administrador pode verificar rapidamente quais usu\u00e1rios falharam nas tentativas de login e com que frequ\u00eancia. Ao descobrirem que uma \u00fanica conta de usu\u00e1rio teve v\u00e1rias tentativas fracassadas em um curto per\u00edodo de tempo, eles puderam concluir que essa conta pode ter sido direcionada. Assim, o script ajuda na detec\u00e7\u00e3o precoce e na corre\u00e7\u00e3o imediata.<\/p>\n<h2>Abordagem alternativa<\/h2>\n<p>H\u00e1 v\u00e1rios m\u00e9todos para rastrear tentativas de login fracassadas. A auditoria de seguran\u00e7a integrada do Windows, por exemplo, permite visualizar os registros de seguran\u00e7a por meio do Event Viewer. Embora essa abordagem seja simples, ela pode consumir muito tempo. Nosso script do PowerShell simplifica o processo, oferecendo uma solu\u00e7\u00e3o mais eficiente e personaliz\u00e1vel.<\/p>\n<h2>Implica\u00e7\u00f5es<\/h2>\n<p>Ao compreender o n\u00famero de tentativas de login com falha, os administradores de TI podem evitar poss\u00edveis viola\u00e7\u00f5es de seguran\u00e7a. Anomalias nos padr\u00f5es de login geralmente s\u00e3o um sinal precoce de atividade mal-intencionada. Portanto, ao agir com base nesses dados, os profissionais podem refor\u00e7ar seus sistemas contra poss\u00edveis amea\u00e7as.<\/p>\n<h2>Recomenda\u00e7\u00f5es<\/h2>\n<ul>\n<li>Verifique se voc\u00ea tem as permiss\u00f5es necess\u00e1rias para obter registros de eventos.<\/li>\n<li>Execute o script regularmente, especialmente nos sistemas que cont\u00eam informa\u00e7\u00f5es confidenciais.<\/li>\n<li>Investigue quaisquer padr\u00f5es de logins com falha e notifique os usu\u00e1rios envolvidos.<\/li>\n<\/ul>\n<h2>Considera\u00e7\u00f5es finais<\/h2>\n<p>Na era das crescentes amea\u00e7as cibern\u00e9ticas, ferramentas como o nosso script do PowerShell s\u00e3o essenciais. Para uma solu\u00e7\u00e3o de seguran\u00e7a abrangente, plataformas como a NinjaOne podem ser integradas, garantindo <a href=\"https:\/\/www.ninjaone.com\/pt-br\/endpoint-management\/monitoramento-remoto-e-alertas\/\">o monitoramento e o gerenciamento em tempo real<\/a>. O NinjaOne, combinado com scripts proativos como o discutido, fornece defesa adicional contra amea\u00e7as cibern\u00e9ticas.<\/p>\n","protected":false},"author":35,"featured_media":142613,"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-809297","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\/809297","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=809297"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/142613"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=809297"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=809297"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=809297"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}