Como usar o PowerShell para localizar com eficiência arquivos OST grandes demais

No local de trabalho digitalizado de hoje, o gerenciamento eficaz dos espaços de armazenamento nos sistemas de computador é fundamental. Como dependemos cada vez mais da comunicação digital, uma ferramenta em que muitos profissionais confiam é o Microsoft Outlook. Com o uso prolongado, os arquivos OST (Outlook Offline Storage Table) podem aumentar significativamente de tamanho, ocupando potencialmente grandes quantidades de espaço em disco. Aqui, apresentamos um script do PowerShell que ajuda os profissionais de TI a localizar arquivos OST de tamanho excessivo

Histórico

O arquivo OST é essencialmente uma cópia dos itens da caixa de correio do Exchange Server. Com o passar do tempo, à medida que mais dados são acumulados, esses arquivos podem aumentar, o que representa desafios de armazenamento. Especialmente para profissionais de TI e provedores de serviços gerenciados (MSPs), manter o controle sobre esses arquivos grandes é essencial para garantir o desempenho ideal do sistema e gerenciar o armazenamento com eficiência. Não se trata apenas de liberar espaço; trata-se de entender o comportamento do usuário, otimizar os recursos e evitar possíveis problemas.

O roteiro

<#
.SYNOPSIS
    Find large OST files in the user's folder or recursively under C:.
.DESCRIPTION
    Find large OST files in the user's folder or recursively under C:.
.PARAMETER MinSize
    The minimum file size. This expects the file size to be in gigabytes.
.PARAMETER AllFolders
    Will search all folders under C:.
.EXAMPLE
     -MinSize 50
    Search for OST files larger than 50GB in each user's Outlook folder.
.EXAMPLE
     -AllFolders -MinSize 50
    Search for OST files larger than 50GB under C: recursively.
.OUTPUTS
    String[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Exit code 1: If at least 1 OST was found larger than MinSize
    Exit code 0: If no OST's where found larger than MinSize
    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()]
    [double]
    $MinSize = 50,
    [switch]
    $AllFolders
)

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)
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    $script:Found = $false

    if ($AllFolders) {
        $FoundFiles = Get-ChildItem C: -Filter *.ost -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.Length / ($MinSize * 1GB) -gt 1 }
        $FoundFiles | Select-Object FullName, Length | ForEach-Object {
            $Name = $_.FullName
            $Size = $_.Length
            Write-Host "$Name $Size bytes"
        }
        # If you wish to automatically remove the file(s) uncomment the line below. Do note that this is permanent! Make backups!
        # $FoundFiles | Remove-Item -Force -Confirm:$false
        if ($FoundFiles) {
            $script:Found = $true
        }
    }
    else {
        $UsersFolder = "C:Users"
        $Outlook = "AppDataLocalMicrosoftOutlook"
        Get-ChildItem -Path $UsersFolder | ForEach-Object {
            $User = $_
            $Folder = "$UsersFolder$User$Outlook"
            if ($(Test-Path -Path $Folder)) {
                $FoundFiles = Get-ChildItem $Folder -Filter *.ost | Where-Object { $_.Length / ($MinSize * 1GB) -gt 1 }
                $FoundFiles | Select-Object FullName, Length | ForEach-Object {
                    $Name = $_.FullName
                    $Size = $_.Length
                    Write-Host "$Name $Size bytes"
                }
                # If you wish to automatically remove the file(s) uncomment the line below. Do note that this is permanent! Make backups!
                # $FoundFiles | Remove-Item -Force -Confirm:$false
                if ($FoundFiles) {
                    Write-Verbose "Found"
                    $script:Found = $true
                }
            }
        }
    }

    if ($script:Found) {
        exit 1
    }
    exit 0
}
end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

O script pode ser compartimentado em várias áreas principais:

  • Sinopse e descrição: Fornece uma visão geral do objetivo do script, que é localizar arquivos OST grandes na pasta de um usuário ou recursivamente em C:.
  • Parâmetros: Determina os detalhes da pesquisa. Isso inclui o tamanho mínimo do arquivo (em GB) e a possibilidade de pesquisar todas as pastas em C:.
  • Verificação da elevação: Antes de se aprofundar na pesquisa de arquivos, o script verifica se há privilégios administrativos. Sem esses direitos, o script não pode sondar níveis mais profundos do sistema.
  • Lógica de pesquisa de arquivos: Dependendo dos parâmetros escolhidos, o script procura em todas as pastas em C: por arquivos OST maiores do que o tamanho especificado ou restringe a pesquisa à pasta do Outlook de cada usuário.
  • Saída: Se forem encontrados arquivos OST grandes demais, o script imprimirá o caminho completo e o tamanho em bytes. Além disso, o script tem linhas comentadas para excluir esses arquivos – essa ação é deixada a critério do profissional de TI.

Casos de uso em potencial

Imagine uma administradora de TI, Jane, em uma empresa de grande porte. Ela recebe reclamações de vários departamentos sobre o atraso do sistema e a diminuição do desempenho. Após alguns testes de diagnóstico, Jane identifica problemas de armazenamento – vários arquivos grandes ocupando espaço essencial. Com esse script, Jane pode identificar rapidamente os arquivos OST de tamanho excessivo e determinar o melhor curso de ação, seja arquivando, excluindo ou realocando os arquivos.

Comparações

Embora existam ferramentas e softwares baseados em GUI que fornecem análise de disco, a vantagem desse script do PowerShell é sua especificidade e seu potencial de automação. Ele visa diretamente os arquivos OST e pode ser incorporado a fluxos de trabalho de automação maiores, ao contrário de muitas ferramentas de terceiros que fornecem visões gerais mais amplas sem o mesmo nível de personalização.

Implicações

Localizar e gerenciar arquivos OST grandes é mais do que um exercício de armazenamento. Ele aborda a segurança de TI. Arquivos OST grandes demais podem ser indicativos de acúmulo de dados ou até mesmo de violações de dados, em que grandes quantidades de dados são exportadas. O gerenciamento proativo desses arquivos pode reduzir os possíveis riscos.

Recomendações

  • Sempre faça backup dos dados antes de executar scripts que possam excluir arquivos.
  • Execute rotineiramente esses scripts para manter o desempenho ideal do sistema.
  • Não remova o comentário da opção de exclusão, a menos que tenha certeza das ramificações.

Considerações finais

Gerenciar arquivos grandes, especialmente arquivos OST, pode ser uma tarefa difícil. Mas ferramentas como o NinjaOne oferecem soluções robustas para o gerenciamento geral de TI. Juntamente com scripts personalizados, como o detalhado aqui, os profissionais podem garantir a eficiência do sistema, a otimização do armazenamento e a minimização de riscos no cenário de TI em constante evolução.

FAQs

Embora o script identifique e liste arquivos OST grandes, há uma linha comentada para exclusão. Se não for comentado, o script removerá os arquivos identificados.

Sim, o script espera o parâmetro de tamanho do arquivo em gigabytes.

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