Como limpar com segurança um disco rígido do Windows com o PowerShell

Na era atual de segurança de dados, o descarte adequado de dados em discos rígidos é crucial. Para os profissionais de TI e os provedores de serviços gerenciados (MSPs), é essencial ter ferramentas confiáveis para essas tarefas. Nesta postagem do blog, vamos nos aprofundar nos detalhes de um script versátil do PowerShell projetado para uma limpeza de disco segura e eficiente. Também forneceremos dicas essenciais para garantir a execução bem-sucedida e a remoção de dados.

O poder do PowerShell para gerenciamento de disco

O PowerShell, a poderosa linguagem de script da Microsoft, oferece amplos recursos para gerenciar e proteger dados. Com suas funcionalidades robustas, como a capacidade de formatar discos e limpar discos rígidos, o PowerShell se torna uma ferramenta inestimável para qualquer pessoa que lide com tarefas frequentes de gerenciamento de dados.

Liberando o potencial do script do PowerShell para limpeza remota

O script do PowerShell em discussão foi criado para executar uma limpeza remota em um dispositivo. Ele é capaz de executar vários métodos, cada um fornecendo níveis variados de exclusão de dados e redefinição do sistema para atender a diferentes requisitos de segurança de dados.

Mas como você garante que esse script seja executado corretamente e que todos os dados sejam apagados com êxito do disco rígido? Aqui estão algumas dicas:

  1. Verifique a compatibilidade: Certifique-se de que o sistema de destino seja compatível com o método escolhido. Por exemplo, os métodos “WipeProtected” e “WipePersistUserData” são compatíveis apenas com versões específicas do Windows 10 ou superiores.
  2. Verificar o nome do computador: O parâmetro ComputerName precisa corresponder ao nome do computador em que o script está sendo executado. Se isso não acontecer, o script será encerrado sem fazer nenhuma alteração. A chave ComputerNameBypass pode ser usada para substituir isso.
  3. Teste antes da implementação: Sempre teste o script em um ambiente controlado antes de implantá-lo em um ambiente de produção. Isso ajuda a identificar e corrigir quaisquer problemas antes que eles afetem os sistemas essenciais.
  4. Monitorar a execução do script: Fique de olho na execução do script. Preste atenção a todos os erros ou exceções lançados pelo script. Essas mensagens podem fornecer informações valiosas sobre quaisquer problemas que possam surgir.
  5. Verify Data Wipe (Verificar limpeza de dados): Após a execução do script, verifique se a limpeza de dados foi bem-sucedida. Isso pode ser feito tentando recuperar dados da unidade. Se a recuperação for impossível, o apagamento de dados pode ser considerado bem-sucedido.
  6. Documentar o processo: Mantenha um registro de todo o processo, desde a execução do script inicial até a verificação da limpeza de dados. Essa documentação pode ser um recurso valioso para referência futura ou em caso de auditorias.

O roteiro: Limpeza remota de um dispositivo Windows

 #Requires -Version 5.1

<#
.SYNOPSIS
    Remote Wipe a device.
.DESCRIPTION
    Remote Wipe a device via InvokeMethod from a Cim Session. doWipe, doWipeProtected, doWipePersistUserData, and doWipePersistProvisionedData are supported.
    See examples for how to use each.
.EXAMPLE
    -Method Wipe -ComputerName "PC-001"
    Runs the doWipe method. Equivalent to running "Reset this PC > Remove everything" from the Settings app, with Clean Data set to No and Delete Files set to Yes.
    ComputerName needs to match the computer name of the computer the script is running on. If it doesn't then the script will exit, doing nothing.
.EXAMPLE
    -Method Wipe -ComputerNameBypass
    Runs the doWipe method. Equivalent to running "Reset this PC > Remove everything" from the Settings app, with Clean Data set to No and Delete Files set to Yes.
    Will bypass the computer name check and run regards less.
.EXAMPLE
    -Method WipeProtected -ComputerName "PC-001"
    Runs the doWipeProtected method. Performs a remote reset on the device and also fully cleans the internal drive.
    Windows 10 build version 1703 and above.
    ComputerName needs to match the computer name of the computer the script is running on. If it doesn't then the script will exit, doing nothing.
.EXAMPLE
    -Method WipePersistUserData
    Runs the doWipeProtected method. Equivalent to selecting "Reset this PC > Keep my files" when manually starting a reset from the Settings app.
    Windows 10 build version 1709 and above.
    ComputerName needs to match the computer name of the computer the script is running on. If it doesn't then the script will exit, doing nothing.
.EXAMPLE
    -Method WipePersistProvisionedData
    Runs the doWipeProtected method. Provisioning packages in the %SystemDrive%ProgramDataMicrosoftProvisioning folder will be retained and then applied to the OS after the reset.
    The information that was backed up will be restored and applied to the device when it resumes.
    ComputerName needs to match the computer name of the computer the script is running on. If it doesn't then the script will exit, doing nothing.
.NOTES
    Reference: https://docs.microsoft.com/en-us/windows/client-management/mdm/remotewipe-csp
    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 (
    [Parameter(Mandatory = $true)]
    [ValidateSet("Wipe", "WipeProtected", "WipePersistProvisionedData", "WipePersistUserData")]
    [String]
    $Method,
    [Parameter()]
    [String]
    $ComputerName,
    [Parameter()]
    [switch]
    $ComputerNameBypass
)

# ComputerNameBypass was used, continue on.
if ($PSBoundParameters.ContainsKey("ComputerNameBypass") -and $ComputerNameBypass) {
    Write-Host "Bypassing Computer Name check."
}
else {
    # If computer name matches, continue on.
    if ($ComputerName -notlike $env:COMPUTERNAME) {
        Write-Error "Computer Name does not match."
        exit 1
    }
}

# Check if the requested Method is supported or not
$BuildVersion = [System.Environment]::OSVersion.Version.Build
if ($BuildVersion -lt 1703 -and $Method -like "WipeProtected") {
    Write-Host "WipeProtected is only supported on Windows 10 build version 1703 and above."
    exit 1
}
if ($BuildVersion -lt 1709 -and $Method -like "WipePersistUserData") {
    Write-Host "WipePersistUserData is only supported on Windows 10 build version 1709 and above."
    exit 1
}

$session = New-CimSession

$params = New-Object Microsoft.Management.Infrastructure.CimMethodParametersCollection
$param = [Microsoft.Management.Infrastructure.CimMethodParameter]::Create("param", "", "String", "In")
$params.Add($param)

$CimSplat = @{
    Namespace = "rootcimv2mdmdmmap"
    ClassName = "MDM_RemoteWipe"
    Filter    = "ParentID='./Vendor/MSFT' and InstanceID='RemoteWipe'"
}

try {
    $instance = Get-CimInstance @CimSplat
    $session.InvokeMethod($CimSplat["Namespace"], $instance, "do$($Method)Method", $params)
}
catch {
    Write-Error $_
    exit 1
}

 


Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Os scripts do PowerShell, como o discutido nesta postagem do blog, podem ser ferramentas poderosas para profissionais de TI e MSPs, proporcionando eficiência e segurança robusta dos dados. Com uma compreensão clara do script e seguindo essas dicas, você pode garantir uma execução bem-sucedida e a limpeza segura dos dados. No âmbito do gerenciamento de dados, ter essas ferramentas e conhecimentos confiáveis é inestimável.

Você pode estar se perguntando: “E quanto à limpeza de um disco rígido do Mac?”, e nós o ajudamos. Confira nossa postagem no blog sobre“Como limpar um disco rígido do Mac com um script Bash“.

Um clique para proteger sua frota – watch emitir um apagamento remoto e capacitar sua equipe de TI.

Como o NinjaOne pode ajudar

Para as organizações que desejam elevar a segurança de seus dados e o gerenciamento de TI a um novo patamar, a integração de uma solução como o NinjaOne pode fazer uma diferença significativa. Embora os scripts do PowerShell sejam eficientes para tarefas como a limpeza de disco, o gerenciamento desses scripts em um grande número de dispositivos pode ser complicado. O NinjaOne simplifica isso oferecendo recursos de automação e implementação de scripts centralizados. Você pode implementar seus scripts do PowerShell para limpar dados remotamente em vários dispositivos, tudo a partir de um único painel.

Além disso, o NinjaOne oferece relatórios e análises avançados, para que você possa verificar facilmente o sucesso de suas operações de limpeza de dados e manter registros de conformidade. Caso o script tenha problemas ou exceções, o monitoramento em tempo real do NinjaOne o alertará, permitindo uma intervenção rápida. Isso minimiza os riscos e garante que seu processo de remoção de dados seja completo e seguro.

Portanto, seja você um profissional de TI ou um provedor de serviços gerenciados, a integração do NinjaOne às suas práticas de segurança e gerenciamento de dados pode oferecer uma camada extra de eficiência e confiabilidade. Não se trata apenas de executar um script; trata-se de gerenciá-lo de forma eficaz em toda a organização, e o NinjaOne pode ajudá-lo a fazer exatamente isso. Assista a uma demonstração e veja por que o NinjaOne foi eleito o software de gerenciamento de endpoint nº 1 no G2 Crowd.

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

Uso do PowerShell para obter a localização do dispositivo usando a API de geolocalização do Google

Como configurar o Windows Defender SmartScreen usando o PowerShell

Exigir senha após a suspensão em máquinas Windows: Script do PowerShell

Ativar ou desativar o protocolo de área de trabalho remota (RDP) em estações de trabalho usando o PowerShell

Como atualizar as políticas de senha do Windows usando o PowerShell

Gerenciando & Configurando o NETBIOS no Windows 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).