Como habilitar minidumps no Windows usando o PowerShell

A prática de depuração e solução de problemas de sistemas de computador geralmente exige ferramentas e scripts especializados. Um desses métodos, crucial para muitos especialistas em TI, é a utilização de arquivos minidump. Esses arquivos oferecem um instantâneo da memória ativa quando um computador sofre uma pane, fornecendo dados valiosos para análise pós-pane. Este artigo examina um script do PowerShell projetado para automatizar a ativação de minidumps em sistemas Windows.

Histórico

Para profissionais de TI e provedores de serviços gerenciados (MSPs), a capacidade de capturar e analisar dados de falhas é vital. Isso os ajuda a entender por que um sistema falhou e a evitar futuras ocorrências. Os arquivos Minidump, em particular, fornecem dados suficientes sem consumir muito espaço em disco, o que os torna a escolha preferida de muitos especialistas. No entanto, a configuração manual da geração de minidump pode ser entediante, e é aí que entra a automação. Ao usar scripts como o que estamos analisando, os profissionais podem configurar seus sistemas de forma eficiente para gerar minidumps quando necessário.

O roteiro

<#
.SYNOPSIS
    Turn on mini dumps if they are off, if other dumps are already enabled do not change the configuration.
.DESCRIPTION
    Turn on mini dumps if they are off, if other dumps are already enabled do not change the configuration.
    This will enable the creation of the pagefile, but set to automatically manage by Windows.
    Reboot might be needed.
.OUTPUTS
    None
.NOTES
    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()]
param ()

begin {
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
            $PropertyType = "DWord"
        )
        # Do not output errors and continue
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
        if (-not $(Test-Path -Path $Path)) {
            # Check if path does not exist and create the path
            New-Item -Path $Path -Force | Out-Null
        }
        if ((Get-ItemProperty -Path $Path -Name $Name)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = Get-ItemProperty -Path $Path -Name $Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "$Path$Name changed from $CurrentValue to $(Get-ItemProperty -Path $Path -Name $Name)"
        }
        else {
            # Create property with value
            try {
                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "Set $Path$Name to $(Get-ItemProperty -Path $Path -Name $Name)"
        }
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue
    }
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # Reference: https://learn.microsoft.com/en-US/troubleshoot/windows-server/performance/memory-dump-file-options
    $Path = "HKLM:SystemCurrentControlSetControlCrashControl"
    $Name = "CrashDumpEnabled"
    $CurrentValue = Get-ItemPropertyValue -Path $Path -Name $Name -ErrorAction SilentlyContinue
    $Value = 3

    # If CrashDumpEnabled is set to 0 or doesn't exist then enable mini crash dump
    if ($CurrentValue -eq 0 -and $null -ne $CurrentValue) {
        $PageFile = Get-ItemPropertyValue -Path "HKLM:SYSTEMCurrentControlSetControlSession ManagerMemory Management" -Name PagingFiles -ErrorAction SilentlyContinue
        if (-not $PageFile) {
            # If the pagefile was not setup, create the registry entry needed to create the pagefile
            try {
                # Enable automatic page management file if disabled to allow mini dump to function
                Set-ItemProp -Path "HKLM:SYSTEMCurrentControlSetControlSession ManagerMemory Management" -Name PagingFiles -Value "?:pagefile.sys" -PropertyType MultiString
            }
            catch {
                Write-Error "Could not create pagefile."
                exit 1
            }
        }
        Set-ItemProp -Path $Path -Name $Name -Value 3
        Write-Host "Reboot might be needed to enable mini crash dump."
    }
    else {
        Write-Host "Crash dumps are already enabled."
    }
    exit 0
}
end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

O script do PowerShell em foco começa verificando se o sistema tem privilégios de administrador. Isso é fundamental porque as alterações no registro do sistema, conforme pretendido por esse script, exigem essas permissões.

O principal caminho de registro de interesse é HKLM:SystemCurrentControlSetControlCrashControl. Nesse caminho, há uma chave de registro específica, CrashDumpEnabled, que controla o estado da geração de despejos de falhas.

Se essa chave for definida como 0 ou não existir, isso indica que os despejos de colisões não estão ativados. Em seguida, o script executará as etapas para ativar a criação de minidump. Além disso, o script verifica a presença de um arquivo de página e estabelece um, se estiver faltando, pois é um pré-requisito para a criação de minidumps.

Casos de uso em potencial

Considere um profissional de TI, Bob, que trabalha em uma organização de médio porte. Após várias falhas inexplicáveis no sistema, Bob está sob pressão para descobrir a causa principal. Em vez de fazer isso máquina por máquina, Bob implementa esse script em todos os computadores da organização. Essa abordagem proativa garante que, na próxima vez que ocorrer uma falha, Bob terá um arquivo de minidump pronto para análise. Bom trabalho, Bob!

Abordagem alternativa

Tradicionalmente, a ativação da geração de minidump envolve a navegação em vários menus do Windows ou a edição manual do registro, tarefas que consomem muito tempo e são propensas a erros. Esse script se destaca por automatizar o processo, reduzindo assim a chance de erro humano e garantindo uma configuração consistente em várias máquinas.

Implicações

A ativação da geração de minidump é uma faca de dois gumes. Embora ofereça dados valiosos para depuração, pode conter informações confidenciais. Os profissionais de TI devem considerar a possibilidade de criptografar esses arquivos ou garantir que eles sejam armazenados em locais seguros.

Recomendações

  • Sempre teste o script em um ambiente controlado antes de implementá-lo.
  • Revise e limpe regularmente os arquivos de minidump para economizar espaço em disco e manter a privacidade.

Considerações finais

A incorporação de soluções automatizadas, como o script discutido, simplifica as tarefas de gerenciamento de TI. Plataformas como o NinjaOne aumentam ainda mais isso, oferecendo controle centralizado e um conjunto de ferramentas adaptadas às necessidades dos profissionais de TI, garantindo que os sistemas permaneçam otimizados e seguros.

FAQs

O script é compatível com o Windows 10 e o Windows Server 2016 ou mais recente.

Pode ser necessário reiniciar o sistema para finalizar a ativação dos mini-crash dumps.

O script reconhecerá isso e se absterá de fazer alterações.

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 listar todos os grupos aos quais um usuário pertence com o PowerShell

Como acessar e armazenar tamanhos de perfis de usuário do Windows com o PowerShell

Como localizar tentativas de login com falha no Windows usando o PowerShell

Como ativar a inicialização rápida do Windows com o PowerShell

Como habilitar a atualização automática do Windows 11 usando um script personalizado do PowerShell

Como ativar a proteção contra PUA no MS Defender usando o PowerShell

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).