Como aumentar de forma eficiente o tamanho do arquivo de registro de eventos com o PowerShell

Os logs de eventos em plataformas Windows oferecem informações valiosas sobre as operações do sistema e possíveis problemas. Dessa forma, os profissionais de TI precisam de uma maneira de ajustar o tamanho desses registros para acomodar diferentes requisitos. Este artigo se aprofunda em um script do PowerShell criado especificamente para aqueles que querem saber como aumentar o tamanho do arquivo de registro de eventos, garantindo que os sistemas estejam sempre sob vigilância adequada.

Histórico

O PowerShell, a estrutura de automação de tarefas da Microsoft, tornou-se uma ferramenta indispensável para profissionais de TI em todo o mundo. Entre seus inúmeros recursos está a capacidade de modificar as configurações do sistema, incluindo o tamanho dos registros de eventos. Como os sistemas geram grandes quantidades de registros ao longo do tempo, ter a capacidade de ajustar a capacidade de armazenamento desses registros é fundamental para os provedores de serviços gerenciados (MSPs) e administradores de TI.

O roteiro

#Requires -Version 5.1

<#
.SYNOPSIS
    Changes the max size for the specified Event Logs.
.DESCRIPTION
    Changes the max size for the specified Event Logs.
    Common log names used: Security, Application, System
    To get a list of Event Log names from your system you can run:
        Get-WinEvent -ListLog * | Select-Object LogName
.EXAMPLE
     -LogName Security -MaxSize 50MB
    Changes the max log size for Security to 50MB
.EXAMPLE
     -LogName Security, Application, System -MaxSize 50MB
    Changes the max log size for Security, Application, and System to 50MB
.OUTPUTS
    None
.NOTES
    Windows 10 defaults to 20MB / 20480KB

    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By 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.
    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. 
    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. 
    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. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, 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. 
    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. 
    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. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding(SupportsShouldProcess)]
param (
    # Event Log name
    # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/limit-eventlog?view=powershell-5.1#-logname
    [Parameter(Mandatory = $true)]
    [ValidateScript(
        {
            if ( -not $($_ | Where-Object { $_ -in $(Get-WinEvent -ListLog * | Select-Object LogName).LogName }) ) {
                throw "$_ is not a valid Event Log Name."
            }
            else {
                $true
            }
        }
    )]
    [String[]]
    $LogName,
    # The max size of the event log storage in KB.
    # Use KB, MB, or GB after your number like 111MB for example.
    [Parameter(Mandatory = $true)]
    [Int64]
    [ValidateRange(64KB, 4GB)]
    $MaxSize
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    "Used Parameters:"
    $(
        $PSBoundParameters.Keys | ForEach-Object {
            $Key = $_
            $Value = $PSBoundParameters["$_"] -join ', '
            "-$Key $Value"
        }
    ) -join ' '

    # Look for Event log names that don't exist
    if ($($LogName | ForEach-Object { $_ -notin $(Get-WinEvent -ListLog * | Select-Object LogName).LogName })) {
        $InvalidLogNames = $LogName | Where-Object { $_ -notin $(Get-WinEvent -ListLog * | Select-Object LogName).LogName }
        Write-Error "Invalid Log Names Found."
        Write-Host "Invalid Log Names: $($InvalidLogNames -join ', ')"
        exit 1
    }

    "Current Log Sizes:"
    Get-WinEvent -ListLog $LogName | Select-Object LogName, MaximumSizeInBytes | ForEach-Object {
        "$($_.LogName): $($_.MaximumSizeInBytes / 1024)KB"
    }
}
process {
    if ($PSCmdlet.ShouldProcess($($LogName -join ','), "Limit-EventLog")) {
        Limit-EventLog -LogName $LogName -MaximumSize $MaxSize -ErrorAction Stop
        # -ErrorAction Stop will exit and return an exit code of 1
        "Changed Log Sizes to:"
        Get-WinEvent -ListLog $LogName | Select-Object LogName, MaximumSizeInBytes | ForEach-Object {
            "$($_.LogName): $($_.MaximumSizeInBytes / 1024)KB"
        }
    }
    else {
        # If -WhatIf was used then print out what the changes would have been.
        "Would have changed the max log size(s) of: $($LogName -join ',') to $($MaxSize / 1024)KB"
    }
}
end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

O script começa validando seus requisitos de ambiente. Em seguida, ele faz o seguinte:

  • Definições de parâmetros: São estabelecidos parâmetros para especificar os nomes dos registros($LogName) e o tamanho máximo desejado($MaxSize ).
  • Verificação da elevação: Uma função, Test-IsElevated, é usada para garantir que o script seja executado com privilégios administrativos, uma necessidade para modificar as propriedades do registro de eventos.
  • Validação do nome do registro: O script valida se os nomes de registro fornecidos existem no sistema usando o cmdlet Get-WinEvent.
  • Exibir os tamanhos atuais: Antes de fazer qualquer alteração, o script exibe os tamanhos atuais dos logs especificados.
  • Ajuste de tamanho: Se a validação for aprovada e a aprovação do usuário for obtida (com a verificação $PSCmdlet.ShouldProcess ), o cmdlet Limit-EventLog ajustará os tamanhos de registro para o valor desejado.

Casos de uso em potencial

Estudo de caso: Imagine um administrador de TI de uma grande empresa em que os aplicativos essenciais produzem muitos registros diariamente. Regularmente, o registro de aplicativos fica cheio, fazendo com que os eventos mais recentes substituam os mais antigos. Usando esse script, o administrador pode aumentar facilmente o tamanho do registro de aplicativos para garantir que dados importantes não sejam perdidos.

Comparações

Tradicionalmente, para aumentar o tamanho de um registro de eventos, era necessário navegar pela GUI do Event Viewer, clicar com o botão direito do mouse no registro desejado, selecionar “Propriedades” e ajustar o tamanho. O script oferece uma alternativa automatizada, eficiente e com redução de erros. Ele também permite ajustes em lote, um recurso que não é facilmente obtido com métodos manuais.

Implicações

Embora o aumento do tamanho dos registros possa garantir a retenção de dados vitais, ele também tem implicações de armazenamento. Se as unidades do sistema estiverem próximas da capacidade e os registros forem expandidos significativamente, isso poderá resultar em problemas de falta de espaço. Além disso, arquivos de registro maiores podem afetar ligeiramente a velocidade de determinadas consultas de registro.

Recomendações

  • Monitore regularmente o armazenamento após aumentar o tamanho dos registros.
  • Ajuste os tamanhos dos registros somente quando necessário e tenha uma compreensão clara do motivo.
  • Sempre mantenha os registros, especialmente o registro de segurança, em um estado monitorado para identificar possíveis ameaças à segurança.

Considerações finais

Para MSPs e profissionais de TI, ferramentas como o NinjaOne podem ser cruciais ao lidar com o gerenciamento de registros e tarefas relacionadas. O NinjaOne, integrado a scripts como o discutido, pode simplificar ainda mais o gerenciamento do sistema, tornando mais fácil do que nunca garantir a integridade e a segurança do sistema.

FAQs

Sim, especifique um tamanho menor que o atual.

O script executa a validação e fornecerá uma mensagem de erro e, em seguida, será encerrado.

Use a opção -WhatIf ao executar, e o script exibirá as ações sem executá-las.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like

Como habilitar ou desabilitar componentes IPv6 no Windows usando o PowerShell

Como verificar se um caminho existe usando o PowerShell

Como bloquear automaticamente o Windows após a inatividade usando o PowerShell

Como aumentar de forma eficiente o tamanho do arquivo de registro de eventos com o PowerShell

Como usar o PowerShell para enviar notificações de mensagens aos usuários do Windows

Como usar o PowerShell para localizar administradores locais

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • 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.
  • 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.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, 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.
  • 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.
  • 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.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).